Practice 1001
My Solution
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
int a, b, c;
scanf("%d", &a);
scanf("%d", &b);
c = a + b;
int positive = 1;
if(c < 0){
c = -c;
positive = 0;
}
int digit = (int) log10(c) + 1;
if(digit < 4){
if(positive == 1){
printf("%d", c);
} else{
printf("%d", c*(-1));
}
} else {
int temp = (digit-1) / 3;
char res[20];
memset(res, '\0', sizeof(res));
sprintf(res, "%d", c);
for(int j=0; j<temp; j++){
for(int i=digit-1+j; i>digit-3*(j+1)-1; i--){
res[i+1] = res[i];
}
res[digit-3*(j+1)] = ',';
}
if(positive == 1){
printf("%s", res);
} else {
for(int k=digit+temp-1; k>=0; k--) {
res[k+1] = res[k];
}
res[0] = '-';
printf("%s", res);
}
}
return 0;
}
Test Result
Any idea or discussion is highly welcomed.