-1

I am trying to reverse integer values without converting to string and then back to int. Correct me if I'm wrong but that's costly & unnecessary. I tried this function and a console.log within the while and just after it returns, for example, 5 (if n = 5) --- but the return value is 0. Why?

function reverseInt(n) {
  const ten = 10;
  const zero = 0;
  // No need to convert, which is expensive
  let rev_num = zero;
  while (n > zero) {
    rev_num = rev_num * ten + (n % ten);
    n = Math.floor(n / ten);
  }

  return rev_num * Math.sign(n);
}

I was expecting 5, not 0.

smac89
  • 39,374
  • 15
  • 132
  • 179
Passerby
  • 1
  • 2
  • `Math.floor(n / ten)` is `Math.floor(5 / 10)` is `Math.floor(0.5)` is `0`. `Math.sign(n)` is `Math.sign(0)` is `0`. Learn about [how to debug small programs](//ericlippert.com/2014/03/05/how-to-debug-small-programs). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). – Sebastian Simon Dec 19 '22 at 04:05

1 Answers1

0

Math.sign returns 0 since n is 0 at the end of the loop. Extract the sign before iterating instead.

function reverseInt(n) {
  const ten = 10;
  const zero = 0;
  const sign = Math.sign(n);
  n = Math.abs(n);
  let rev_num = zero;
  while (n > zero) {
    rev_num = rev_num * ten + (n % ten);
    n = Math.floor(n / ten);
  }

  return rev_num * sign;
}
console.log(reverseInt(123));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80