版权声明:原创博客,转载请标明出处! https://blog.csdn.net/caipengbenren/article/details/88843198
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
这一题关键的就是加逗号,有两种方法一种是从前往后加逗号,一种是从后往前加逗号,个人比较喜欢从前往后,因为不用特判负数
从前往后,满足(i + 1) % 3 == len % 3;特判最后一位。
#include<iostream>
#include<cmath>
using namespace std;
int main () {
int a, b;
cin >> a >> b;
string c = to_string(a + b);
int len = int(c.length());
string ans = "";
for (int i = 0; i <= len - 1; i++) {
ans += c[i];
if (c[i] == '-') {
continue;
}
if ((i + 1) % 3 == len % 3 && i != len - 1) {
ans = ans + ',';
}
}
cout << ans;
return 0;
}
从后往前,满足 num % 3 == 0,特判0。
#include<iostream>
#include<cmath>
using namespace std;
int main () {
int a, b, c, sign = 0;
cin >> a >> b;
c = a + b;
string ans;
if (c < 0) sign = 1;
if (c == 0) ans = "0";
c = abs(c);
int num = 1;
while(c != 0) {
ans = char(c % 10 + '0') + ans;
c /= 10;
if (num++ % 3 == 0 && c != 0) {
ans = ',' + ans;
}
}
if (sign == 1) {
ans = '-' + ans;
}
cout << ans;
return 0;
}