Can anyone show me where I'm going wrong in my code please? I'm trying to reverse a number without changing it to a string. I've been searching google and looked through the previous questions asked about this topic and from what I can see my code mirrors the other answers.
I've only been able to find code in Java, C, or C++ that do not use the to string method.
In my attempts, when I run the code in the browser console it either gives me an answer of "Infinity" or crashes my browser.
Here's my code...
function reverseNumber(number) {
var revNumber = 0;
while (number > 0) {
revNumber = (revNumber * 10) + (number % 10);
number = number / 10;
}
return revNumber;
}
console.log(reverseNumber(876));
I know it must be some small syntax error but I just don't see it. Any insight would be appreciated. Thanks!
number = number / 10;
inside a while
loop whose condition is number > 0
means that number
will only reach 0 after a very large number of iterations, once number precision fails. (eg. 876 => 87.6 => 8.76 => .876 => .0876...) That's not what you want. You might divide by 10 and drop the decimal part:
function reverseNumber(number) {
var revNumber = 0;
while (number > 0) {
revNumber = (revNumber * 10) + (number % 10);
number = Math.floor(number / 10);
}
return revNumber;
}
console.log(reverseNumber(876));
These works.
Basic Implementation:
function reverse(n)
{
var temp=0;
while(n)
{
temp *= 10;
temp += n%10;
n = Math.floor(n/10);
}
return temp;
}
console.log(reverse(123))
console.log(reverse(456))
console.log(reverse(789))
console.log(reverse(7890))
Inline Basic implementation:
function reverse(n)
{
var reverse=0;
while(n>0) (reverse=reverse*10+n%10, n=Math.floor(n/10));
return reverse;
}
console.log(reverse(123))
console.log(reverse(456))
console.log(reverse(789))
console.log(reverse(7890))
Implementation using arrays.
function reverse(n)
{
var arr=[], reverse=0;
while(n>0) (arr.push(n%10), n=Math.floor(n/10));
while(arr.length) reverse=reverse*10+arr.shift();
return reverse;
}
console.log(reverse(123))
console.log(reverse(456))
console.log(reverse(789))
console.log(reverse(7890))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With