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 ?106≤a,b≤106. 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
不能直接从前往后遍历结果c的各位数字将其一个一个输出,因为考虑输出逗号需要从后往前计算数字个数。
思路:
设置一个存放最终输出结果的字符串。从后往前遍历各位数字,每次将其插在结果字符串的开头。同时计算已经遍历数字的个数,若个数是3的倍数,且当前遍历的数字不是第一位数字,则插入逗号。
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
int main() {
int a;
int b;
cin>>a;
cin>>b;
int c=a+b;
string cString=to_string(c);//int转string
string resultStr="";//输出结果字符串
int count=0;//已遍历数字的个数
//插逗号时,从后往前 遍历数字;一边遍历一边赋值给另一个字符串
int i;//下标
if(c==0)
i=0;
else if(c<0) //c为负数,加一个符号位
i=(1+(int)log10(abs(c)))+1-1;
else
i=(1+(int)log10(abs(c)))-1;
for(; i>=0; i--) {
string insertStr(1,cString.at(i));//char转为string
resultStr.insert(0,insertStr);
count++;
if(count%3==0) {
if(i==0||cString.at(i-1)=='-') { //不能插逗号:i指向元素是第一位数字;i指向元素前面一位为负号
} else {
resultStr.insert(0,",");
}
}
}
cout<<resultStr;
return 0;
}
string::at()返回值为char&类型
string::insert(下标i,字符串)
//字符串插在字符串的下标i后
计算c的位数,c不能为0
1+(int)log10(abs(c))
数据类型转换
string::to_string(c)
//int转string字符串是从第一个字符开始存的: (c=-999,991)cString.at(0)是-
string::insertStr(1,cString.at(i))
//char转为string1+(int)log10(abs(c))不能计算c=0的情况,需要另外处理
解决:
if(c==0)
i=0;
else if(c<0) //c为负数,加一个符号位
i=(1+(int)log10(abs(c)))+1-1;
else
i=(1+(int)log10(abs(c)))-1;
当已遍历数字个数是3的倍数,但不能插逗号的情况:
当前遍历的数字已经是数字串的首个数字:
数字串是正数:当前遍历的数字是第一位(i==0)
数字串是负数:前一位是符号‘ - ’
if(count%3==0) {
if(i==0||cString.at(i-1)=='-') { //不能插逗号:i指向元素是第一位数字;i指向元素前面一位为负号
} else {
resultStr.insert(0,",");
}
}
comma:逗号
原文:https://www.cnblogs.com/musecho/p/12229427.html