ACwing刷题笔记 1473.A+B格式
思路
先将数字转换成字符串,然后遍历字符串,每遍历一个数字将该数字存入一个新的字符串(字符串拼接),每三个字符就打上一个逗号(注意-99999这种,当i=0时不需要打上逗号,因为此时是负号,以及num[i-1] = '-'此时也不需要添加逗号,因为下一个就是负号)
代码
#include<iostream>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int c = a + b;
string num = to_string(c);// 转换成字符串
string res;// 存储转换之后的字符串
for(int i = num.size() - 1,j = 0; i >= 0; i--)
{
res = num[i] + res;// 拼接字符串
j++;
if((j%3==0) && i != 0 && num[i - 1] != '-')
{
res = ',' + res;//添加一个逗号
}
}
cout<<res;
return 0;
}