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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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

我的解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

//解题思路:
//1.计算这两个数的和
//2.通过递归打印
//递归的时候记录当前位置,若该位置后的数的个数能被3整除,则打印逗号

using namespace std;

//正整数的长度
int lenOfNum(int num)
{
int len = 0;

while (num) {
num /= 10;
++len;
}

return len;
}

void _print(int num, int len, int &count)
{
if (num) {
_print(num / 10, len, count);
cout << num % 10;
//若后面的数的个数能被3整除则打印逗号
if (++count != len && (len - count) % 3 == 0) {
cout << ",";
}
}
}

void printFormat(int num)
{
int count = 0; //已打印数的个数
int len = lenOfNum(num);

if (num < 0) {
cout << "-";
num = -num;
}

if (num == 0) {
cout << "0";
}
else {
_print(num, len, count);
}
}

int main()
{
int a, b;

cin >> a >> b;
printFormat(a + b);
cout << endl;

return 0;
}
Author: sphc
Link: https://jkuvw.xyz/archives/c0252f49/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
微信打赏
支付宝打赏