Wednesday, April 10, 2013

10035 - Primary Arithmetic

10035 - Primary Arithmetic

I could've done it using mod%10 but I wanted to do it with arrays. 

#include
#include

#define N 10+1

int main() {
    
    /* 
     size_t strlen ( const char * str );
     Returns the length of the C string str.
     
     The length of a C string is determined by the terminating null-character: 
     A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
     */
    
    int i=0, j=0;
    char inputa[N+1], inputb[N+1]; /* '\0' */
    int a[N], b[N];
    size_t na=0, nb=0; /* size_t is unsigned long */
    int carry=0;

    while(1) {

        scanf("%s %s", inputa, inputb);
        
        if ((inputa[0] == '0') && (inputb[0] == '0'))
            break;
        
        /* init */
        carry=0;
        
        for (i=0; i<N; i++) {
            a[i]=0;
            b[i]=0;
        }
        
        /* copy to integer arrays  */
        na = strlen(inputa);
        nb = strlen(inputb);
        
        j=N-na;
        for (i=0; i
            a[j++] = inputa[i] - '0';
        }
        
        j=N-nb;
        for (i=0; i
            b[j++] = inputb[i] - '0';
        }
        
        /* carry part */
        for (i=N-1; i>=0; i--) {
            if (a[i]+b[i] > 9) {
                carry++;
                a[i-1]++;
            }
        }
        
        /* print */
        if (carry == 0)
            printf("No carry operation.\n");
        else if (carry == 1)
        printf("1 carry operation.\n");
        else
        printf("%d carry operations.\n", carry);

    }
    return 0;
}

No comments:

Post a Comment