Javascript: How to Reverse a Number?

Below is my source code to reverse (as in a mirror) the given number. I need to reverse the number using the reverse method of arrays.

<script>
   
    var a = prompt("Enter a value");
    var b, sum = 0;
    var z = a;
    while(a > 0)
    {
      b = a % 10;
      sum = sum * 10 + b;
      a = parseInt(a / 10);
    }
    alert(sum);
</script>
3

18 Answers

Low-level integer numbers reversing:

function flipInt(n){
    var digit, result = 0

    while( n ){
        digit = n % 10  //  Get right-most digit. Ex. 123/10 → 12.3 → 3
        result = (result * 10) + digit  //  Ex. 123 → 1230 + 4 → 1234
        n = n/10|0  //  Remove right-most digit. Ex. 123 → 12.3 → 12
    }  
  
    return result
}


// Usage: 
alert(
  "Reversed number: " + flipInt( +prompt("Enter a value") ) 
)

The above code uses bitwise operators for quick math

This method is MUCH FASTER than other methods which convert the number to an Array and then reverse it and join it again. This is a low-level blazing-fast solution.

Illustration table:

const delay = (ms = 1000) => new Promise(res => setTimeout(res, ms))
const table = document.querySelector('tbody')

async function printLine(s1, s2, op){
  table.innerHTML += `<tr>
    <td>${s1}</td>
    <td>${s2||''}</td>
  </tr>`
}

async function steps(){
  printLine(123)
  await delay()
  
  printLine('12.3 →')
  await delay()
  
  printLine(12, 3)
  await delay()
  
  printLine('1.2', '3 &times; 10')
  await delay()
  
  printLine('1.2 →', 30)
  await delay()
  
  printLine(1, 32)
  await delay()
  
  printLine(1, '32 &times; 10')
  await delay()
  
  printLine('1 →', 320)
  await delay()
  
  printLine('', 321)
  await delay()
}

steps()
table{ width: 200px; }
td {
  border: 1px dotted #999;
}
<table>
  <thead>
    <tr>
      <th>Current</th>
      <th>Output</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
5

Assuming @DominicTobias is correct, you can use this:

console.log( 
    +prompt("Enter a value").split("").reverse().join("") 
)
4

I was recently asked how to solve this problem and this was my initial solution:


The desired output: 123 => 321, -15 => -51, 500 => 5

function revInt(num) {
// Use toString() to convert it into a String
// Use the split() method to return a new array: -123 => ['-', '1','2','3']
// Use the reverse() method to reverse the new created array: ['-', '1','2','3'] => ['3','2','1','-'];
// Use the join() method to join all elements of the array into a string
  let val = num.toString().split('').reverse().join('');
    // If the entered number was negative, then that '-' would be the last character in
   //  our newly created String, but we don't want that, instead what we want is
  //  for it to be the first one. So, this was the solution from the top of my head.

// The endsWith() method determines whether a string ends with the characters of a specified string
  if (val.endsWith('-')) {
    val = '-' + val;
      return parseInt(val);
  }
      return parseInt(val);
}

console.log(revInt(-123));

A way better solution:

After I gave it some more thought, I came up with the following:

   // Here we're converting the result of the same functions used in the above example to 
// an Integer and multiplying it by the value returned from the Math.sign() function.

// NOTE: The Math.sign() function returns either a positive or negative +/- 1, 
// indicating the sign of a number passed into the argument.   

function reverseInt(n) {
      return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}

console.log(reverseInt(-123));

NOTE: The 2nd solution is much more straightforward, IMHO

1

This is my solution, pure JS without predefined functions.

function reverseNum(number) {
  var result = 0,
    counter = 0;
  for (i = number; i >= 1; i = i / 10 - (i % 10) * 0.1) {
    counter = i % 10;
    result = result * 10 + counter;
  }
  return result;
}

console.log(reverseNum(547793));

Or, as a one-liner ( x contains the integer number to be inversed):

revX=x.toFixed(0).split('').reverse().join('')-0;

The number will be separated into its individual digits, reversed and then reassembled again into a string. The -0 then converts it into a number again.

2

Firstly, I don't think you are using an array to store the number. You are using a java script variable.

Try out this code and see if it works.

var a = prompt("Enter a value");
var z = a;
var reverse = 0;
while(z > 0)
{
    var digit = z % 10;
    reverse = (reverse * 10) + digit;
    z = parseInt(z / 10);
}
alert("reverse = " + reverse);
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.