见证自己的成长
题目如下
过程中出现了好几次问题,具体参考另一篇博文
做题过程出现的弱智然而我不会的问题
解析见注释
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
//转化成字符串处理
string i2s(int c)
{
string s;
stringstream ss;
ss << c;
ss >> s;
return s;
}
int main()
{
int a,b;
scanf("%d %d", &a, &b);
int c = a + b;
//负号单独处理
int ct = c;
if( c < 0) {
printf("-");
ct = -c;
}
string str = i2s(ct);
//出现的问题3
str.c_str();
//把字符串逆着加逗号,然后存入ans中正着输出
string ans = "";
int len = str.length();
int cnt = 0;
for(int i=len-1; i>=0; i--) {
cnt++;
ans += str[i];
if(cnt == 3) {
ans += ",";
len++;
cnt = 0;
}
}
for(int i=len-1; i>=0; i--) {
if(ans[len-1] == ',') {
len -= 1;
}
else {
printf("%c", ans[i]);
}
}
return 0;
}
全例通过!
另外,要是仔细审题的话,会发现数字最大是7位数,所以,加逗号只有两种情况
- A+B之后7位数,加两个逗号就可以
- 只加一个逗号
然后就可以简单的对数字进行拆分,然后输出逗号