美文网首页
甲级-1001 A+B Format (20 分)

甲级-1001 A+B Format (20 分)

作者: 梦终无痕_311d | 来源:发表于2019-09-27 16:56 被阅读0次

    题目:

    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

    解题思路:

    将两个数相加后的计算结果直接转换为 string 类型,然后从后往前遍历,每循环三次插入一个逗号。
    虽然在 string 中间进行插入操作会消耗大量的时间,但题目中限定了数字的长度,因此不必考虑时间问题。

    代码:

    编译器:C++(g++)

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        int a,b;
        cin>>a>>b;
        int sum=a+b;
        string str=to_string(sum);
        int i=0;
        if('-'==str[0])
        {
            i=1;
        }
        for(int j=str.size()-1,count=0;j>i;--j)
        {
            ++count;
            if(3==count)
            {
                str.insert(j,",");
                count=0;
            }
        }
        cout<<str<<endl;
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:甲级-1001 A+B Format (20 分)

          本文链接:https://www.haomeiwen.com/subject/flotyctx.html