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 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
思路
由于a,b的范围在−106到106 ,因此a+b的范围最多在 ·−2x106到2x106之间,因此我们我们可以用至多三个数字储存按照逗号分割的和。
例如:1123312,可以用1,123,312这三个数字储存
代码
注意在这里使用n1,n2,n3的形式来输出结果,当和小于0的时候要先转化为正数在计算,同时还要依次判断首位的数字是否为0来决定是否输出
#include "stdio.h"
int main()
{
int a,b;
scanf("%d %d",&a,&b);
int c=a+b;
bool flag=(c>=0);//because remainder operation may have erro for the negative numbers
//so we need to flag wheather the sum is negative and change the negative to positive
if(!flag)
c=-c;
int n1,n2,n3;//three number to represent the sum
n3=c%1000;n2=c/1000%1000;n1=c/1000000%1000;
if(!flag)
printf("-");
if(n1!=0)
{
printf("%d,%03d,%03d\n",n1,n2,n3);
}
else if(n2!=0)
{
printf("%d,%03d\n",n2,n3);
}
else
{
printf("%d\n",n3);
}
return 0;
}
git仓库:1001 A+B Format