标签:div 字符 otto a+b insert end -- The mes
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).
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.
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.
-1000000 9
-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 }
(未完待续)
标签:div 字符 otto a+b insert end -- The mes
原文地址:https://www.cnblogs.com/jcchan/p/11502703.html