PTA Advanced Level / 1001 A+B Format (20 分)

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

首先读懂题意:计算a+b的值,按照标准格式输出他们的和。这个标准格式是数字一定要每三个之间用逗号隔开(除非数字位数小于四位)

题目对数据的范围给出限定   -10^6 – 10^6

 

题目已经限制了数据范围 所以不需要考虑大数和long的情况,可以直接用int做。

下面给出思路以及代码(想吐槽的是为什么PTA不支持 to_string和reverse函数)

 1 #include <iostream>
 2 #include <string.h>
 3 #include <stdio.h>
 4 using namespace std;
 5 int main()
 6 {
 7     //用int输入,并且相加,处理得到的和sum
 8     //进行int转字符串操作,得到一个字符串。
 9     //做一次字符串反转
10     //分情况讨论,有两种情况。
11     //第一种是最后一个字符是数字,代表这个是正数,对其从前往后遍历,将其赋值到另一个字符数组里,当n*3+1次的时候,做两次赋值处理,第一次进行给逗号,第二次赋值给数字。
12     //第二种是最后一个字符是负号,代表这个是负数对其从前往后遍历,将其赋值到另一个字符数组里,当n*3+1次的时候,做两次赋值处理,第一次进行给逗号,第二次赋值给数字。当最后一次的时候要进行一次特判,如果执行到n*3+1的时候,并且是最后一个字符,就不给逗号。
13     int a, b, sum;
14     //string strSum;
15     char strSum[100], TstrSum[100];
16     cin >> a >> b;
17     sum = a + b;
18     //strSum = to_string(sum);
19     sprintf(TstrSum, "%d", sum);
20     //strrev(strSum);//这个只能放char[]
21 
22 
23 
24 
25     //reverse(strSum.begin(), strSum.end());//字符串反转
26     //cout << strSum << endl;
27 //    int len = strSum.size(), j=0;
28     int j = 0;
29     int len = strlen(TstrSum);
30     char chSum[100];
31     int k = len - 1;
32     for (int i = 0; i < len; i++)
33     {
34         strSum[i] = TstrSum[k--];
35     }
36     strSum[len] = '';
37     memset(chSum, '', sizeof(chSum));
38     if ( '-' == strSum[len-1])//负数
39     {
40         for (int i = 0; i < len; i++)
41         {
42             if (0 == i %3 && i != len-1 && i>=                   3)
43             {
44 //                cout << ',';
45                 chSum[j++] = ',';
46             }
47             chSum[j++] = strSum[i];
48             //cout << strSum[i];
49         }
50     }
51     else {//正数
52         for (int i = 0; i < len; i++)
53         {
54             if (0==i%3 && i>=3)
55             {
56                 chSum[j++] = ',';
57 //                cout << ',';
58             }
59 //            cout << strSum[i];
60             chSum[j++] = strSum[i];
61         }
62     }
63     int clen = strlen(chSum);
64     for (int i = clen-1; i >= 0; i--)
65     {
66         cout << chSum[i];
67     }
68 
69 }
原文地址:https://www.cnblogs.com/wu199723/p/11561427.html