题目:
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
思路:
计算两个整数之和,以标准形式输出,即每三位输出一个‘,’。因为要求的位数有限,可以使用取巧的方法,其结果最大值是7位数,只用考虑两个逗号。另外,结果的符号可以另外考虑,最后只要考虑整数的标准输出就可以了。没有采用取巧的方法,将计算结果转换为字符串。第一次计算的结果为不带逗号的字符串,第二次从后面遍历,每三个字符插入一个逗号。最后在将字符串输出就可以了。注意考虑三位数和六位数的情况,即防止数字开头出现逗号。
问题:
注意输出格式和数字的范围,本题不需要考虑int的范围。在写数数字转到字符串时没有考虑到0的情况,最后作特殊处理。
代码:
#include<iostream>
#include<string>
using namespace std;
int fang(int k) {
int a = 1;
for (int i = 0; i < k; ++i) {
a = a * 10;
}
return a;
}
int main()
{
int A, B;
cin >> A >> B;
int ru = A + B;
string str;
int falg = 0;
for (int i = 7; i >= 0; --i) {
if (ru < 0) {
ru = -ru;
cout << "-";
}
int num = 0;
if (falg == 0)
{
if (ru - fang(i) >= 0) {
falg = 1;
}
}
if (falg == 1) {
num = ru / fang(i);
ru = ru - num*fang(i);
char a = '0' + num;
str = str + a;
}
}
int count = 3;
string b;
for (int i = str.size() - 1; i >= 0; --i) {
count--;
b = b + str[i];
if (count == 0 && i != 0) {
count = 3;
b = b + ',';
}
}
if (b.empty()) {
cout << "0";
}
else {
for (int i = b.size() - 1; i >= 0; --i) {
cout << b[i];
}
}
return 0;
}