甲级|1001.A+B Format
2018-10-20 本文已影响0人
yzbkaka
题目描述
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).
输入描述
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6 ≤a,b≤ 10^6. The numbers are separated by a space.
输出描述
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.
输入例子
-1000000 9
输出例子
-999,991
我的代码
#include<stdio.h>
int main(){
int a,b,sum,i,j=0,t=0;
char c[100];
scanf("%d %d",&a,&b);
sum=a+b;
if(sum>-100&&sum<1000){ //如果没有达到4位数则是直接输出
printf("%d",sum);
}
else{
if(sum>1000){ //如果是一个大于0且达到4位数的值
while(sum!=0){
i=sum%10;
sum=sum/10;
c[j]=i+'0'; //存进字符串中
j++;
}
if(j%3==0){ //如果位数能直接被3整除,则从尾到头输出
for(i=j-1;i>=0;i--){
printf("%c",c[i]);
t++;
if(t%3==0&&i!=0){ //输出标点
printf(",");
}
}
}
else{
if(j==4){ //如果是个4位数
printf("%c",c[j-1]);
printf(",");
for(i=j-2;i>=0;i--){
printf("%c",c[i]);
}
}
if(j==5){ //如果是个5位数
printf("%c%c",c[j-1],c[j-2]);
printf(",");
for(i=j-3;i>=0;i--){
printf("%c",c[i]);
}
}
if(j==7){
printf("%c",c[j-1]);
printf(",");
for(i=j-2;i>=0;i--){
printf("%c",c[i]);
t++;
if(t%3==0&&i!=0){
printf(",");
}
}
}
}
}
else{ //如果是一个小于0且大于4位数的值
sum=-sum;
while(sum!=0){
i=sum%10;
sum=sum/10;
c[j]=i+'0'; //存进字符串中
j++;
}
if(j%3==0){ //如果位数能直接被3整除,则从尾到头输出
printf("-"); //加上负号
for(i=j-1;i>=0;i--){
printf("%c",c[i]);
t++;
if(t%3==0&&i!=0){ //输出标点
printf(",");
}
}
}
else{
if(j==4){ //如果是个4位数
printf("-");
printf("%c",c[j-1]);
printf(",");
for(i=j-2;i>=0;i--){
printf("%c",c[i]);
}
}
if(j==5){ //如果是个5位数
printf("-");
printf("%c%c",c[j-1],c[j-2]);
printf(",");
for(i=j-3;i>=0;i--){
printf("%c",c[i]);
}
}
if(j==7){
printf("-");
printf("%c",c[j-1]);
printf(",");
for(i=j-2;i>=0;i--){
printf("%c",c[i]);
t++;
if(t%3==0&&i!=0){
printf(",");
}
}
}
}
}
}
return 0;
}
我的分析
这一道题是由于题目中对a,b大小的限制,所以可以很轻易的列出来一些特殊情况。我这里就是将sum所得的位数来分情况讨论,如果是能被3整除的位数(3,6)则可以每输出三个数打一个“,”。如果是4位数或者是7位数,则是先手动输出第一个数然后打一个“,”,然后再在循环里面正常输出。5位数则是手动输出两个数后打“,”,然后正常的输出即可。注意如果sum是负数的话算法不变,只先在前面加上“-”即可。