Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a number without making it a string in Javascript [duplicate]

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!

like image 961
smallDisgruntledDog Avatar asked Dec 06 '22 11:12

smallDisgruntledDog


2 Answers

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));
like image 118
CertainPerformance Avatar answered Dec 25 '22 23:12

CertainPerformance


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))
like image 25
Vignesh Raja Avatar answered Dec 25 '22 23:12

Vignesh Raja