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

思路:题目意思是两数相加后的结果每三位加一个逗号,我的做法是把取余的每位都保存在字符栈中,每取三位加一个逗号,最后出栈即可,区分下正数负数和零的情况即可。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using namespace std;
int main()
{
    char sta[20];
    int top=-1;
    int a,b,sum;
    cin>>a>>b;
    sum=a+b;
    int flag=0;
    if(sum!=0)
    {
        if(sum<0)
        {
            sum=-sum;
            cout<<'-';
        }
        while(sum)
        {
            if(flag%3==0)
            {
                sta[++top]=',';
                flag=0;
            }
            ++flag;        
            sta[++top]='0'+sum%10;
            sum/=10;
        }
        while(top!=0)
            cout<<sta[top--];
        --top;
        cout<<endl;
    }
    else
        cout<<0<<endl;
}

打个小广告

欢迎加入我的知识星球「基你太美」,我会在星球中分享 AucFrame 框架、大厂面经、AndroidUtilCode 更详尽的说明…一切我所了解的知识,你可以通过支付进入我的星球「基你太美」进行体验,加入后优先观看星球中精华的部分,如果觉得星球的内容对自身没有收益,你可以自行申请退款退出星球,也没必要加我好友;如果你已确定要留在我的星球,可以通过扫描如下二维码(备注:基你太美+你的星球昵称)加我个人微信,方便我后续拉你进群(PS:进得越早价格越便宜)。

我的二维码