码迷,mamicode.com
首页 > 其他好文 > 详细

PTA (Advanced Level)1001.A+B Format

时间:2019-10-20 10:41:08      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:line   ups   com   cto   NPU   standard   ber   a+b   and   

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

PTA (Advanced Level)1001.A+B Format

标签:line   ups   com   cto   NPU   standard   ber   a+b   and   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!