PTA (Advanced Level)1001.A+B Format

时间:2019-10-20
本文章向大家介绍PTA (Advanced Level)1001.A+B Format,主要包括PTA (Advanced Level)1001.A+B Format使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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
思路
  • 将数字转换为字符串,每隔3个输出一个,,要注意的点写在代码注释里了
代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    int ans = a + b;
    if(ans / 1000 == 0)     //只有3位
        cout << ans;
    else
    {
        vector<char> v;
        int cnt = 0;
        int t;
        char tmp;
        if(ans < 0)
         {
            cout << '-';
            ans = -ans;
         }
        while(ans)
        {
            t = ans % 10;
             tmp = t + '0';
            v.push_back(tmp);
            ans /= 10;
            cnt++;
            if(cnt == 3 && ans)     //为了避免输出形如-,999,991这样的答案
            {
                v.push_back(',');
                cnt = 0;
            }
        }
        for(int i=v.size()-1;i>=0;i--)
            cout << v[i];
    }
    return 0;
}

引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

原文地址:https://www.cnblogs.com/MartinLwx/p/11706810.html