PAT-A-1001. A+B Format (20)

来源:互联网 发布:杰奇cms 编辑:程序博客网 时间:2024/05/03 09:05

Question

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的结果用标准形式输出

Code

从后往前每隔三个添加一个逗号,注意负号的情况,绝对值在1000以内的可以直接输出

#include<iostream>#include<string>#include<algorithm>using namespace std;int main(){  int a, b;  cin >> a >> b;  int sum = a + b;  string str = to_string(a + b);  if (sum<1000 && sum>-1000)  {    cout << str << endl;    return 0;  }  string res;  int count = 0;  for (int i = str.size()-1; i >=0 ; i--)  {    res.push_back(str[i]);    if (i == 0)      break;    count++;    if (count == 3 && str[i-1]!='-')    {      count = 0;      res.push_back(',');    }  }  reverse(res.begin(), res.end());  cout << res << endl;  return 0;}
0 0
原创粉丝点击