PAT甲级1001 A+B Format
题目
生词
comma n.逗号;停顿
题目大意
按要求输出a+b的结果,输出格式:每三个数就要加个逗号
题中的坑(可能不算坑但我踩了):是从后往前加逗号!!也就是说9999的正确输出应该是9,999而不是999,9
思路1:
参考柳婼大神的题解柳婼大神博客
把a+b的和转为字符串s~除了第⼀位是负号的情况,只要当前位的下标i满⾜(i + 1) % 3 == len %3并且i不是最后⼀位,就在逐位输出的时候在该位输出后的后⾯加上⼀个逗号
代码
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string s = to_string(a + b);
int len = s.length();
for (int i = 0; i < len; i++) {
cout << s[i];
if (s[i] == '-') continue;
if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ",";//神奇公式MARK
}
return 0;
}
未理解之处:(i + 1) % 3 == len % 3 这个神奇的公式是怎么退出来的没搞明白,暂时先记下。
思路二(自己的思路,较复杂)
前言:
在看完柳婼大神的题目分析后,立即尝试自己写代码。自己最开始采用的方法是使用变量cont来记录已经输出的字符个数,然后如果count%3==0 && 不是最后一个数字就输出‘,’。但是没注意到加逗号应该是从后往前加。于是卡题很久
思路:
还是用count计数,但是for循环从后往前读取字符串
if判断条件是:
1.count%3==0
2.(i!=0) //第一个字符前不加逗号
3.s[i-1]!='-' //如果这个条件不加 可能出现 -,999,999的情况
代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b,count=0;
string s,res="";
cin>>a>>b;
s=to_string(a+b);
for(int i=s.length()-1;i>=0;i--){
res=res+s[i];
if(s[i]=='-')continue;
count++;
if(count%3==0&&(i!=0)&&s[i-1]!='-')res=res+",";
}
reverse(res.begin(),res.end());
cout<<res;
return 0;
}