1. 程式人生 > >PAT (Advanced level) 1001 A+B Format (20 分)

PAT (Advanced level) 1001 A+B Format (20 分)

1001 A+B Format (20 分)

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 ≤ 10​6​​. 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 <iostream>
#include <string>
#include <cstring> #include <algorithm> #include <cmath> using namespace std; int main() { int a, b; cin >> a >> b; int c = a + b; string sign = c < 0 ? "-" : ""; c = fabs(c); string sumAbs = to_string(c); reverse(sumAbs.begin(), sumAbs.end()); string result;
for (int i = 0; i < sumAbs.size(); i++) { if (!i || i % 3) result += sumAbs[i]; //如果i不是0,或者i不能被3整除,直接加在後面 else //如果能被3整除, 先加一個","再把數字加在後面 { result += ","; result += sumAbs[i]; } } result += sign; //最後加上符號 reverse(result.begin(), result.end()); //將結果倒轉回來 cout << result << endl; return 0; }

思路

首先,題目說這裡的a和b是絕對值小於106的整數,所以不用考慮大數加減的演算法(C++ int型別一共32位,取值範圍在 -231 ~ 231 之間),直接兩數相加,判斷並儲存符號在sign字串中,然後求絕對值,使用to_string函式轉成string型別儲存在sumAbs中,使用reverse函式將sumAbs倒轉,分情況將值加在result後面,最後加上之前儲存的符號sign,再倒轉回來。

有兩個坑

  1. 本來想用string.insert(size_t pos, const string& str) 把“, ”直接插入到字串中間,但是因為插入後字串變長了這樣再找下標能被3整除的位置就會出錯,使題目變麻煩。。。
    @[TOC](這裡寫自定義目錄標題)
  2. 本來想把
			result += ",";
			result += sumAbs[i];

寫成

			result += ("," + sumAbs[i]);

但是cout輸出答案時發現答案變成了-99991而不是-999,991於是我發現這裡有個細節,因為","是一個char,sumAbs[i]也是一個char 兩個char型別相加並不是連線而是ASCII碼相加,所以出錯。
a = -1000000 b = 9
以上