Search code examples
c++functionrecursionnumbersdigits

How to change a number's digits in a recursive function? C++


I have to input a number n, an a digit and a b digit and output the number n with all the a digits in it replaced by a b one. For example:

Input:
n = 1561525
a = 5
b = 9

Output:
n = 1961929

Should be recursive ! I didn't post any code as I've done it in a non-recursive way but apparently it's not even close to what I need.

Thanks for the help !


Solution

  • Check this, it works but maybe it is to much C

    int convert(int num, int a, int b)
    {
        if( num )
        {
            int res = convert(num/10,a,b);
            int t = num%10;
            res *=10;
            t = t == a ? b:t;
            res = res + t;
            return res;
        }
        return 0;
    }
    

    Divide by 10 the initial number, until nothing left of it, and then construct it again replacing a with b.