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
题型分类:字符串处理
题目大意:题目要求计算两个数的和,每三位要输出一个“逗号”。
解题思路:采用string来处理,同时对负号进行特殊处理。result变量中存入最终的输出答案,其中result变量赋值时,高位存入sum变量的低位,每存入3位数字后,存入一个“,”。输出时倒序输出即可。
#include <string>
using namespace std;
int main() {
int a, b;
scanf("%d %d", &a, &b);
int sum = a + b;
if(sum < 0){ //负数则输出负号,并且将和转变为正数(除去符号更方便处理)
printf("-");
sum = -sum;
}
string result, tempStr = to_string(sum);
int cnt = 0;
for(int i = tempStr.length() - 1; i >= 0; i--, cnt++){
if(cnt != 0 && cnt % 3 == 0){ //每隔3位加上一个","
result += ',';
}
result += tempStr[i];
}
for(int i = result.length() - 1; i >= 0; i--){
printf("%c", result[i]);
}
return 0;
}