Advanced Level) Practice-1001"/>
PTA PAT (Advanced Level) Practice-1001
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;
}
更多推荐
PTA PAT (Advanced Level) Practice-1001
发布评论