地址 https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400
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 Specification: Each input file contains one test case. Each case contains a pair of integers a and b where
?10?6≤a,b≤106 ?? . The numbers are separated by a space. Output Specification: 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
题目大意是
两数相加 使用每个三个数字打印一个‘,‘的形式将其显示出来
解答
这个主要是熟悉 字符串与数字之间的转换逆转换。
模拟题,主要注意数字和字符串的转换,并且每隔三个数字就要加上一个逗号
但是逗号任意一边只有负号或者是起点 或终点则不必添加逗号(-199 199 )
#include <iostream> #include <string> #include <algorithm> using namespace std; int n, m; int main() { cin >> n >> m; int k = n + m; string ans; int flag = 0; if (k < 0) {flag = 1;k = abs(k);} else if (k == 0) {cout << 0 << endl;return 0;} int count = 0; while (k != 0) { int tmp = k % 10;k = k / 10; ans += (char)(‘0‘ + tmp); count++; if (count % 3 == 0 && k!=0) {ans += ‘,‘;} } reverse(ans.begin(),ans.end()); if (flag) ans.insert(ans.begin(), ‘-‘); cout << ans << endl; return 0; }
原文:https://www.cnblogs.com/itdef/p/14387174.html