Home > other >  Reverse Interger with recursion
Reverse Interger with recursion

Time:12-27

I am not able to find why this code is not giving proper result.for Exp:- if i provide that num as 132 then rev it should be 231. it is not giving the expected.

function reverse(num, rev) {
    if (num != 0) {
        let mod = num % 10;
        rev = rev * 10   mod;
        num = Math.floor(num / 10);
        console.log(num, rev);
        reverse(num, rev);
    }
    return rev;
}

CodePudding user response:

Just a small change, you need to return the reverse(num, rev) inside the if condition

function reverse(num, rev = 0) {
    if (num != 0) {
        let mod = num % 10;
        rev = rev * 10   mod;
        num = Math.floor(num / 10);

        return reverse(num, rev);
    }
    return rev;
}

console.log(reverse(1234))

CodePudding user response:

You could use a recursive function as you started and Abito Prakash, but this solution using a string split and array reverse is likely faster with large numbers:

function reverse(num) {
  return parseInt(num.toString().split('').reverse().join(''), 10);
}
console.log(132, '=>', reverse(132));
console.log(1234, '=>', reverse(1234));
console.log(1234567890123456, '=>', reverse(1234567890123456));

Output:

132 => 231
1234 => 4321
1234567890123456 => 6543210987654321
  • Related