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

转载于:https://www.cnblogs.com/firstmiki/p/6259845.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值