题目
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 −106 ≤a,b≤106 . 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
思路
- 先处理3位一个逗号:
把a和b的sum按位分解开,放进char栈里,并且如果没遇到最后一个数字就入栈3个就放入一个逗号。 - 后处理正负号和0:
如果是负数则输入‘-’,正数不显示符号位,0直接输出程序结束
Code
#include<stdio.h>
#include<math.h>
main()
{
int a,b,sum,asum,top;
int flag=0;
char stack[1000000];
scanf("%d %d",&a,&b);
sum=a+b;
asum=abs(sum);
top=0;
while(asum>0)
{
stack[top++]=asum%10+'0';
asum/=10;
flag++;
if(flag==3)
{
flag=0;
if(asum>0)
stack[top++]=',';
}
}
if(sum<0)
stack[top]='-';
else if(sum>0)
top--;
else
{
printf("0");
return 0;
}
while(top>=0)
printf("%c",stack[top--]);
}