题目描述
实现
码前思考
需要使用STL里的string
,然后需要将数字转换成字符串,需要用to_string()
,这次终于没忘记了,插入逗号要用insert()
,还有获取子串substr()
;
代码实现
#include <iostream>
#include <string>
using namespace std;
int a,b,c;
int main(){
scanf("%d %d",&a,&b);
c = a+b;
string output = to_string(c);
bool flag=false;
if(output[0]=='-'){
output = output.substr(1);
flag=true;
}
//cout<<output<<endl;
//从末尾开始insert
for(int i=output.size()-3;i>0;){
output.insert(i,",");
i = i-3;
}
output = flag ? "-"+output : output;
cout<<output<<endl;
return 0;
}
码后反思
有STL还是舒服啊,之前没用STL,是下面这样的:
#include<stdio.h>
#include<string.h>
#include<math.h>
int main(){
long long a,b,c;
scanf("%lld",&a);
scanf("%lld",&b);
char d[20];
c = a + b;
if(c<1000 && c> -1000){
printf("%ld",c);
}
else{
if(c<0){
printf("-");
}
c = fabs(c);
int num = 0;
int len = 0;
char n;
do{
if(num != 0 && num%3 == 0)
{
d[len] = ',';
len++;
num = 0;
}
n = c % 10 + '0';
c = c / 10;
d[len] = n;
num++;
len++;
}while(c!=0);
for(int i = len-1;i>=0;i--){
printf("%c",d[i]);
}
}
return 0;
}
相当于是按位遍历加逗号。