PAT Advanced level 1001 A+B Format

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



虽然放假了但是并不能愉快划水qwq
嗯,因为作死报了个PAT于是现在开始刷PAT的题了。。。
希望开学前能刷完吧(大概

第一题,原来a+b还能出成这样。。。
计算一下数字位数,然后一位一位输出,每三位加逗号
注意正负号以及和为0的情况

#include<iostream>
#include<cstdio>
using namespace std;
void output(int x){
    if(!x){printf("0");return;}
    int sign=(x<0?-1:1);
    int len=0,a[10];
    while(x){
        a[len]=x%10;
        ++len;
        x/=10;
    }
    if(sign<0)printf("-");
    for(int i=len-1;i>=0;--i){
        printf("%d",sign*a[i]);
        if(i%3==0 && i)printf(",");
    }
}
int main(){
    int a,b;
    scanf("%d%d",&a,&b);
    output(a+b);
    return 0;
} 
 

猜你喜欢

转载自www.cnblogs.com/wypx/p/12188371.html
今日推荐