Domanda

I need to write to recursive functions, where in the first one, I need to sum two integers digit by digit. I have written some code, but it gives me the final result multiplied by 10. I see that the problem happens because when I sum first two digits I multiply them by 10.

The second function must count number of carries in the sum. Meaning if two digits were 3 and 8, then when we sum them we get 11, which is result 1, and carry 1. Simply, I just need to count how many carries occur.

Please note that I assume that both numbers have same number of digits.

#include <stdio.h>

int sum(int a, int b)
{
    int temp = (a%10) + (b%10);
    static int mul = 1;

    if(a == 0 && b == 0)
        return 0;
    else
    {
        mul *= 10;
        return (mul*temp) + sum(a/10, b/10);
    }
}

int carry(int a, int b)
{
    static int counter = 0;

    if((a%10) + (b%10) > 9)
        counter++;

    if(a == 0 && b == 0)
        return counter;

    carry(a/10, b/10);

}

int main()
{
    int a = 1941;
    int b = 2282;

    int result = sum(a, b);
    printf("%d\n", result);

    int car = carry(a, b);
    printf("%d\n", car);

    return 0;
}
È stato utile?

Soluzione

return (mul*temp) + sum(a/10, b/10);

Should be:

return temp + 10*sum(a/10, b/10);

You don't need a static variable, Static variables are used to implement a global state whose lifetime extent the entire process. That's not something desirable and should only be used at last resort. Furthermore, that's definitely not what you need here, using static variables to implement your solution will leads to functions that only work the first time they are called.

You should use the recursive property of your algorithm to aggregate the result:

int sum(int a, int b)
{
    if(a == 0 && b == 0) {
        return 0;
    }
    else
    {
        return (a%10) + (b%10) + 10*sum(a/10, b/10);
    }
}

sum(1941, 2282) will expand to :

sum(1941, 2282)
1 + 2 + 10*sum(194, 228)
1 + 2 + 10*(4 + 8 + 10*sum(19, 22))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*sum(1, 2))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*sum(0, 0))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*0)

You should use the same approach for carry :

int carry(int a, int b)
{
    if(a == 0 && b == 0) {
        return 0;
    }
    else if((a%10) + (b%10) > 9) {
        return 1 + carry(a/10, b/10);
    }
    else {
        return carry(a/10, b/10);
    }
}

carry(1941, 2282) will expand to :

carry(1941, 2282)
0 + carry(194, 228)
0 + 1 + carry(19, 22)
0 + 1 + 1 + carry(1, 2)
0 + 1 + 1 + 0 + carry(0, 0)
0 + 1 + 1 + 0 + 0
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top