1

I tried to use a recursive function to reverse a number it works but for one call only it's because of scoping i guess but i don't know how to fix it

let num;
let reversed='';
let result; 

function reverseNum(n){ 
 
  for(let i =0; i<n; i++){  
    num = n%10; // get the last digit e.g 352 %10 = 2
    reversed+= num
    result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
    reverseNum(result);
    if(result ===0){ 
        break;
    } 
  }
  return reversed;
}

3 Answers 3

2

You need the num, reversed, and result variables to be created anew each time the function is called externally. Here's one simple tweak, by defining the recursive function inside the top reverseNum function:

function reverseNum(n) {
  let num;
  let reversed = '';
  let result;
  const recurse = (n) => {
    for (let i = 0; i < n; i++) {
      num = n % 10; // get the last digit e.g 352 %10 = 2
      reversed += num
      result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
      recurse(result);
      if (result === 0) {
        break;
      }
    }
    return reversed;
  };
  return recurse(n);
}

console.log(reverseNum(1234));
console.log(reverseNum(1234));

But a more elegant method would be:

function reverseNum(n, str = String(n)) {
  const thisDigit = str[str.length - 1];
  const recursiveResult = str.length === 1 ? '' : reverseNum(str.slice(0, str.length - 1));
  return Number(thisDigit + recursiveResult);
}

console.log(reverseNum(1234));
console.log(reverseNum(1234));

Sign up to request clarification or add additional context in comments.

3 Comments

Why doesn't it work if num, reversed, and result were created inside the function body without defining the recursive function inside the top reverseNum function ?
Because You need the num, reversed, and result variables to be created anew each time the function is called externally.. In your original code, on subsequent calls, the old variables from the previous call are being used.
Note that your "more elegant method" will fail when the digits include zero: reverseNum (8675309) => 935768
0

function reverse(number){
        let index = 0 ; 
        let reversed = '';
        let max = `${number}`.toString().length-1;
        while(index  <= max ){
             reversed += `${number}`.charAt(max-index)
             index ++;
        }
        return reversed;
}

console.log(reverse(546))

Comments

0

CertainPerformance has explained why your code wasn't working.

Here is another implementation, one I find reasonably simple:

const reverseNum = (n) =>
  n < 10
    ? String(n)
    : String (n % 10) + reverseNum (Math .floor (n / 10))


console .log (reverseNum (8675309))

Note that this returns a String rather than a Number. If we wanted to, we could make this a private function and make a public function one which called this and converted the result back into a number. But that would have the weird effect that reversing, say, 1000 would yield 1, since 0001 is simplified to 1. And that would mean that when you reverse again, you don't get anything like your original value. So I choose to keep with a String.

Of course if we're going to do String reversal, perhaps we're better off just using a String reversal function in the first place:

const reverseStr = (s) =>
  s.length == 0
    ? ''
    : reverseStr (s .slice (1)) + s [0]

const reverseNum = (n) => 
  reverseStr (String(n))
  
console .log (reverseNum (8675309))

Or if we weren't interested in doing this recursively, we could just write the more common string reversal function:

const reverseStr = (s) =>
  s .split ('') .reverse () .join ('')

const reverseNum = (n) =>
  reverseStr (String (n))
  
console .log (reverseNum (8675309))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.