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.