1001. A+B Format (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Calculate a + b and output thesumin standard format-- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input
Each input filecontainsone test case. Each casecontainsa pair of integers aand b where -1000000 <= a, b <= 1000000. The numbers are separated byaspace.
Output
For each test case, you should output thesumofaand b inoneline. The sum must be written inthe standard format.
Sample Input
-10000009
Sample Output
-999,991
提交代码
解题思路
1.先将和转话为字符串,然后利用stack从后往前加上,,最后在从堆顶依次输出。
AC代码
#include<cstdio>#include<iostream>#include<algorithm>#include<math.h>#include<sstream>#include<string>#include<stack>usingnamespacestd;
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(false);
int a,b,sum;
cin >> a >> b;
sum = a + b;
if (sum<0) {
//printf("-");cout<<"-";
}
//将和转化为字符串
sum = abs(sum);
string str;
stringstream ss;
ss << sum;
ss >> str;
int len =str.length();
//利用stack加入,stack<char> keep;
int cnt = 0;
while (len--) {
cnt++;
keep.push(str[len]);
if (cnt%3==0) {
keep.push(',');
}
}
//依次输出char out = keep.top();
if (out==',') {
keep.pop();
}
while (!keep.empty()) {
char out = keep.top();
cout << out;
keep.pop();
}
cout << endl;
return0;
}