1001 A+B Format (20 分)
Calculate 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 and where . The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of and in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
读题:给出两个有符号整数,将它们按照三位一个逗号的方式输出,有负号打负号。整数的范围是-1000000到1000000。
解题思路:因为逗号的判断是按位判断的,如果顺序遍历每一位会很麻烦,用字符串的函数to_string()将数字转换为字符串,已知字符串的大小,就可以从后往前数,不用把逗号存到字符串里,直接打印就好了。
AC代码
#include<iostream>
#include<string>
using namespace std;
int main(){
int a,b,c;
string result;
cin >> a >> b;
c = a+b;
result = to_string(c);
for( int i = 0 ; i < result.size() ; i ++ ){
cout << result[i];
if( abs(c) >= 1e6 && i == result.size() - 7 ){
cout << ',';
}
if( abs(c) >= 1e3 && i == result.size() - 4 ){
cout << ',';
}
}
return 0;
}
0 条评论