原题:
计算 a+b 并以标准格式输出总和----也就是说,从最低位开始每隔三位数加进一个逗号(千位分隔符),如果结果少于四位则不需添加。
输入格式
共一行,包含两个整数 a 和 b。
输出格式
共一行,以标准格式输出 a+b 的和。
数据范围
我的题解:
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cin>>a>>b;
c=a+b;
string tem;
tem=to_string(c);
string res;
int i,j;
for(i=tem.size()-1,j=0;i>=0;i--)
{
res=tem[i]+res;
j++;
if(j%3==0&&i&&tem[i-1]!='-')
{
res=','+res;
}
}
cout<<res;
}
优秀题解:
#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 && num[i - 1] != '-') res = ',' + res;
}
cout << res << endl;
return 0;
}
作者:小张同学
链接:https://www.acwing.com/solution/content/10472/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。