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

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。