Jasmine Jasmine - 19 days ago 10
C Question

Add or subtract two numbers represented as Strings without using int, double, long, float, etc

My assignment for this question has already passed and I guess I misunderstood the question altogether by using numerical data types in some parts of my code. So I'm just curious as to how to solve this problem of adding/subtracting subtract two numbers represented as Strings without using numerical data types. By numerical data types, I just mean int, double, long, etc and everything needs to stay in String form.

Answer

Here is a function that performs addition of numbers in string format into an array of char, assumed to be sufficiently large and different from a and b:

char *add_numbers(char *dest, const char *a, const char *b) {
    size_t lena = strlen(a);
    size_t lenb = strlen(b);
    size_t len = lena > lenb ? lena + 1 : lenb + 1;
    char carry = 0;        

    dest[len] = '\0';
    while (lena > 0 && lenb > 0) {
        char digit = a[--lena] - '0' + b[--lenb] + carry;
        carry = 0;
        if (digit > '9') {
            carry = 1;
            digit -= 10;
        }
        dest[--len] = digit;
    }
    if (lenb > 0) {
        lena = lenb;
        a = b;
    }
    while (lena > 0) {
        char digit = a[--lena] + carry;
        carry = 0;
        if (digit > '9') {
            carry = 1;
            digit -= 10;
        }
        dest[--len] = digit;
    }
    if (carry) {
        dest[--len] = '1';
    } else {
        for (;; len++) {
            dest[len - 1] = dest[len];
            if (dest[len] == '\0')
                break;
        }
    }
    return dest;
}

No int, double, long, float. The number is not converted into numerical format, the operation is performed one digit at a time, in string format.