PAT甲级 1001. A+B Format (20)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT甲级 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

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

题目意思:
输入俩int型数字,对数字大小范围有规定,计算和,并且按照标准格式输出。标准格式为:从末尾数字开始数,每隔三个有一个","号,如果数字本来就不足四位,则前面不加","号。


题解:
计算俩数字和之后,转换成string型,由于数字长度也不大,于是把数字给分解了,放到一个map里,看代码23和24行,比如最后一位就是m[1]="X",这样再输出的时候,如果m[i]的i值为3的倍数且小于str去除"-"号之后的长度,则加","输出。
 1 #include <iostream>
 2 #include <map>
 3 #include <strstream>
 4 using namespace std;
 5 map <int,string> m;
 6 int main()
 7 {
 8     int a,b;
 9     while(cin>>a>>b){
10         int sum = a+b;
11         //把int型的sum转换成string型的str
12         strstream ss;
13         string str;
14         ss << sum;
15         ss >> str;
16         int str_length = str.length();
17         if(sum<0){
18             str_length--;
19             //删除str的-号
20             str.erase(0,1);
21         }
22         //把str逆向输入到m[i]中,str最后一位是m[1]
23         for(int i=1; i<=str_length; i++){
24             m[i]=str.at(str_length-i);
25         }
26         if(sum<0) cout<<"-";
27         for(int i=str_length; i>=1; i--){
28             if(i%3==0&&i<str_length) cout<<","<<m[i];
29             else cout<<m[i];
30         }
31         cout<<endl;
32     }
33     return 0;
34 }

 代码:https://git.oschina.net/firstmiki/PAT-Advanced-Level-Practise

以上是关于PAT甲级 1001. A+B Format (20)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 甲级 1001 A+B Format

PAT甲级 1001. A+B Format (20)

PAT 甲级 1001 A+B Format (20)(20 分)

PAT甲级——1001 A+B Format (20分)

pat甲级 1001 A+B Format

PAT甲级(1001:A+B Format)