Search code examples
arraysctype-conversioncharansi-c

Add two large numbers as strings


I'm not adding "real" code here code snippets, because I've tried so many variations - with varying success - that I'm just going to use C-like pseudo code.

===

I want to add two numbers that exceed ANSI C's largest long long (such as two 50 digit numbers)

The idea is that I would use two char[] arrays and do a classic pen-and-paper style addition by converting each character of the two addends to ints, adding and carrying the tens, and then assigning the results as a char again to a char[] array.

The problems I'm running into is converting the char to int (which always fails) ... and then adding the result to a another text array. Trying to add a character to the char result[]using result[i] = "5" or even its ascii value result[i] = 53 always fails.

pseudo code

int add(char *n1, char *n2){
    // examples (Intentionally not the same length)
    // n1     = "12345678901234567890"
    // n2     =      "987654321098765"
    char result[100]; // array for resulting added ints as char
    int r = 100; // The index (set to end) for the result array 
    result[r] = 0; // Assign the char-halt to END of the result
    int carry = 0; //  for carrying the 10s
    maxlength = <length of largest addend> // (sizeof(n)/sizeof(n[0])) doesnt work because pointers

    // start at end (right end) of arrays and move towards start (left end)
    // each loop takes one character, starting at the far RIGHT (end) of the string array
    // i = (maxlength - 1) to skip stop "0"
    for (int i = (maxlength - 1); i >= 0; i--) { 
        a1 = int()n1[i] // doesnt return correct value in tests. Neither does a1 = n1[i]-0
        a2 = int()n1[i] // doesnt return correct value in tests. Neither does a1 = n1[i]-0
        int asum = a1 + a2 + carry

        // carry all the tens
        carry = 0; // reset carry
        while (asum > 10){
            carry += 10; 
            asum -= 10; 
        }
        result[r] = char()asum 
        r -= 1 // Move result index one to the LEFT
    }
}    

Solution

  • The problems I'm running into is converting the char to int ...

    The C Standard guarantees that the 10 characters '0' to '9' hold consecutively and increasing values:

    5.2.1 Character sets

    [...]

    3 Both the basic source and basic execution character sets shall have the following members: the 10 decimal digits

    0 1 2 3 4 5 6 7 8 9

    [...] the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

    Look at this and get the concept:

    #include stdio.h>
    
    int main(void)
    {
      char c = '7'; 
      int i = c - '0'; 
    
      printf("c = %c, i = %d\n", c, i); 
    }