PAT菜鸡笔记1001 A+B Format
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 −106≤a,b≤106. 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–。
#include<iostream>
#include<vector>
using namespace std;
int main() {
int a, b;
vector<int> s;
scanf("%d %d", &a, &b);
int sum = a + b;
if (sum == 0)
{
printf("0\n");
return 0;
}
if (sum < 0)
{
sum = -sum;
printf("-");
}
while (sum != 0)
{
a = sum % 10;
sum /= 10;
s.push_back(a);
}
for (int i = s.size() - 1; i >= 0; i--)
{
printf("%d", s[i]);
if (i % 3 == 0 && i != 0)
printf(",");
}
printf("\n");
return 0;
}