PAT甲级1001
【题目】
1001 A+B Format (20 point(s))
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 −106≤a,b≤106. 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然后让其相加并将其的和每3个用“,”隔开
【注意】
1.这个逗号隔开的形式是比如 : 1111+1111 那么应该输出的结果是2,222而不是222,2(因为我起初这么想然后错了........)
2.还要注意形如 :
- 111,
- ,111
- 111,
1 #include<iostream> 2 #include<cmath> 3 #include<stack> 4 using namespace std; 5 int main() { 6 int a,b; 7 while (cin >> a >> b) { 8 int ans = a + b; 9 10 //处理负号 11 if (ans < 0) cout << "-"; 12 ans = abs(ans); 13 14 //用栈来存储 15 stack<int> s; 16 int cnt=0; 17 18 //如果ans是0就直接输出了吧 19 if (ans == 0) { 20 cout << 0 << endl; 21 continue; 22 } 23 24 while (ans) { 25 s.push(ans % 10); 26 ans /= 10; 27 } 28 int mk; //标记前面第几个digit会有逗号用的,因为这边不一定是第三个 29 int array[100000]; 30 while (!s.empty()) { 31 array[++cnt] = s.top(); 32 s.pop(); 33 } 34 35 mk = cnt % 3; 36 for (int i = 1; i<=cnt; ++i) { 37 //为了防止最后会多出个逗号就这么来了,本来还想再用个cnt2来判断 38 if ((i-mk-1>0)&&(!((i-mk-1)%3))) cout<<","; 39 else if (i-1==mk&&i-1>0)cout<<","; 40 cout << array[i]; 41 } 42 cout << endl; 43 } 44 }