• 1001. A+B Format (20)


    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
    
    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

    分析:首先将和按3位分开,自然想到了对1000取余的办法。于是按照二进制的除二取余的思路将和分开。需要注意的是,对1000取余后得到的结果可能不是三位数,而是两位或者一位,这个时候就需要在输出的时候在前面补零凑够三位。这里用到了栈。

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <stack>
    using namespace std;
    
    int main()
    {
        long a,b,c;
        cin>>a>>b;
        c=a+b;
        if(c==0)
        {
            cout<<0<<endl;
            return 0;
        }
        int flag=1;
        if(c<0)
        {
            c*=-1;
            flag=-1;
        }
        stack<long> ans;
        while(c>0)
        {
            ans.push(c%1000);
            c/=1000;
        }
        if(flag==-1)
        {
            printf("-");
        }
        //输出第一个数
        printf("%ld", ans.top());
        ans.pop();
        while(ans.size()>0)
        {
            printf(",%03ld",ans.top());
            ans.pop();
        }
        cout<<endl;
        return 0;
    }
  • 相关阅读:
    2020.11.9
    2020.11.6
    2020.11.5
    2020.11.2
    建站纪念
    退役记——CCC2020&CCO2020
    BZOJ2809&&LG1552 APIO2012派遣(线段树合并)
    BZOJ4668 冷战(LCT维护最小生成树)
    BZOJ3926&&lg3346 ZJOI诸神眷顾的幻想乡(广义后缀自动机)
    BZOJ4566&&lg3181 HAOI找相同字符(广义后缀自动机)
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6385926.html
Copyright © 2020-2023  润新知