JavaScript: How to reverse a number?

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>

Leave a Comment