PAT1001 A+B Format HERODING的PAT之路
Calculate a + b and output the sum in standard format — that is, the digits must be separated into groupsof three by commas (unless there are less than four digits).InputEach input file contains one t
Calculate a + b and output the sum in standard format — that is, the digits must be separated into groups
of three by commas (unless there are less than four digits).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a,
b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the
standard format.
Sample Input
-1000000 9
Sample Output
-999,991
题目大意:
计算A+B的和,然后从个位开始每三位输出一个‘,’(标准格式输出)
解题思路:
通过了解题目大意就可以知道解决这道题还需要字符串处理操作,首先就是计算,因为位数少直接上int即可,把计算结果保存为string类型,按顺序输出,在输出过程中要判断位数,如果当前位数模3余1且不是个位,那么在这后面输出‘,’,代码如下:
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string res = to_string(a + b);
int len = res.length();
for(int i = 0; i < len; i ++) {
cout << res[i];
if(res[i] == '-') continue;
if((len - i) % 3 == 1 && i != len - 1) cout << ",";
}
return 0;
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)