当前位置:   article > 正文

PTA PAT (Advanced Level) Practice-1001_pta顶级题目

pta顶级题目

1001 A+B Format (20 分)
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10
​6
​​ ≤a,b≤10
​6
​​ . The numbers are separated by a space.

Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:
-1000000 9
Sample Output:
-999,991

思路:用栈数据结构就行了,还有就是注意a + b等于零的时候要输出0

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<stack>
using namespace std;
stack<char> p;
int main()
{
    int a, b, t = 1, flag = 0;
    cin >> a >> b;
    if(a+b < 0){
        flag = 1;
    }
    a = abs(a+b);
    if(a == 0){
        cout << "0";
    }
    else{
        while(a != 0){
            char c = a%10 +'0';
            p.push(c);
            if(t%3 == 0 && a/10 != 0){
                p.push(',');
            }
            t++;
            a /= 10;
        }
    }
    if(flag)
        cout << "-";
    while(!p.empty()){
        printf("%c",p.top());
        p.pop();
    }
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/627417
推荐阅读
相关标签
  

闽ICP备14008679号