码迷,mamicode.com
首页 > 编程语言 > 详细

PAT甲级题目1-10(C++)

时间:2019-09-10 20:54:28      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:div   字符   otto   a+b   insert   end   --   The   mes   

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

解题思路:

首先看到问题里面a和b的值都只在$[-10^6,10^6]$,因此用整型就足够完成加法运算,因此这里可以直接保存结果为字符串result。接下来只需要倒序遍历字符串,每3个字符就插入1个逗号,需要注意的是,最后一组不能用逗号将符号和数字分离了,比如题目里的输出:-999,991,就不能写成-,999,991。因此需要加一个判断最开头的一位是否为符号即可。

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 }

 

(未完待续)

 

PAT甲级题目1-10(C++)

标签:div   字符   otto   a+b   insert   end   --   The   mes   

原文地址:https://www.cnblogs.com/jcchan/p/11502703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!