PAT Grade topic 1-10 (C ++)

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,b10​^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

Problem-solving ideas:

First see a and b in question which only $ [--10 ^ 6, 10 ^ 6] $, so it is sufficient to use integer addition operation is completed, so there can be saved directly to a String result. Next, just reverse to traverse the string, each three characters is inserted a comma, to be noted that, the last group can not be a comma separated symbols and numbers, such as the subject in the output: -999,991, it can not be written - , 999,991. Therefore need to add a judgment whether the very beginning of a symbol to.

Code:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main(){
 6     int a,b;
 7     cin>>a>>skipws>>b;
 8     string result = to_string(a+b);
 9     int number = 1;
10     int length = result.length();
11     string comma = ",";
12     for(int i = length-1;i>=1;i--){
13         if(number % 3 == 0 && isdigit(result[i-1])){
14             result = result.insert(i,comma);
15             number = 1;
16         }
17         else{
18             number++;
19         }
20     }
21     cout<<result<<endl;
22     return 0;
23 }

 

(To be continued)

 

Guess you like

Origin www.cnblogs.com/jcchan/p/11502703.html