【PAT甲級】1001 A+B Format
阿新 • • 發佈:2018-11-03
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 −106≤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
個人思路
水題略過
程式碼實現
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <algorithm> #include <iostream> #define ll long long #define ep 1e-2 using namespace std; const int maxn = 15; int main() { int a, b; cin >> a >> b; int sum = abs(a + b), cnt = 0; string sum_str = ""; if (a + b == 0) { sum_str += '0'; } else { while (sum != 0) { cnt ++; sum_str = char((sum%10)+'0') + sum_str; sum /= 10; if (cnt % 3 == 0 && sum != 0) sum_str = ',' + sum_str; } if (a + b < 0) sum_str = '-' + sum_str; } cout << sum_str << endl; return 0; }
總結
學習不息,繼續加油