1001 A+B Format

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 –​​106a,b106​​. 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

思路一:

      这道题目的意思是计算a+b的和并以千分位的形式输出。注意到a,b的取值范围为–​​106a,b106,可以对a,b和sum的大小进行分类讨论,sum的位数最大为7位数,即输出的结果所用的comma最多为两个,所以分三种情况讨论。这种解法有点投机取巧,对a,b的取值有较大的限制。尝试新思路,见思路二。

AC Code:

 1 #include <cstdio>
 2 using namespace std;
 3 
 4 void print(int n) {
 5     if(n < 0) {
 6         printf("-");
 7         n = -n;
 8     }    
 9     if(n >= 1000000){
10         printf("%d,%03d,%03d", n/1000000, (n%1000000)/1000, n%1000);
11     }else if(n >= 1000){
12         printf("%d,%03d", n/1000, n%1000);
13     }else {
14         printf("%d", n);
15     }
16 }
17 int main() {
18     int a, b;
19     int sum;
20     scanf("%d %d", &a, &b);
21     sum = a + b;
22     print(sum);
23     return 0;
24 } 

思路二:

这道题难点在于如何三位输出,可以利用数组存放每一个数,然后倒序输出,当下标为3的倍数的时候,加入“,”即可。

AC Code:

 1 #include <cstdio>
 2 using namespace std;
 3 
 4 void print(int n) {
 5     if(n < 0) {
 6         printf("-");
 7         n = -n;
 8     }    
 9     int num[20] = {0};
10     int length = 0;
11     do{
12         num[++length] = n % 10;
13         n = n / 10;
14     }while(n != 0);
15     
16     //处理高位 
17     int temp = length % 3;
18     if(temp) {
19         
20         for(int i = temp; i > 0; i--) {
21             printf("%d", num[length--]);
22         }
23         if(length > 0)
24             printf(",");
25     }
26     
27     int count = 0;
28     for(int i = length; i > 0; i--) {
29         printf("%d", num[i]);
30         count++;
31         if(count == 3 && i > 1){
32             count = 0;
33             printf(",");
34         }
35     }
36 }
37 int main() {
38     int a, b;
39     int sum;
40     scanf("%d %d", &a, &b);
41     sum = a + b;
42     print(sum);
43     return 0;
44 } 
原文地址:https://www.cnblogs.com/lulizhiTopCoder/p/10398338.html