PAT-甲級-1001-A+B Format

Practice 1001

PAT甲級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

PAT甲級1001
Any idea or discussion is highly welcomed.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章