天天看點

PAT -- 甲級1001(A+B Format)

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

給兩個在[-1e6, 1e6]範圍内的數字,計算a+b的值,結果每遇到3位前面打上一個逗号’,’,使其按照這個格式輸出。

思路:模拟,利用stringstream容器直接将數字轉成字元串。

#include <bits/stdc++.h>
using namespace std;

int a,b,res;

string itos(int res) {
  stringstream s;
  s << res;
  return s.str();
}

int main() {
  string ans;
  cin >> a >> b;
  res = a + b;
  ans = itos(res);
  int j = 1;
  for (int i = ans.size() - 1; i > 0; i--, j++) {
    if (j % 3 == 0 && (res >= 0 || res < 0 && i > 1)) {
      ans.insert(i, 1, ',');
    }
  }
  cout << ans << endl;
  return 0;
}