Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to reverse a number?

Tags:

javascript

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.

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);
like image 649
surendran prabhakaran Avatar asked Jun 27 '16 12:06

surendran prabhakaran


People also ask

How do I reverse a number in JavaScript?

JavaScript program to reverse a number: let rev = 0; let num = 123456; let lastDigit; while(num != 0){ lastDigit = num % 10; rev = rev * 10 + lastDigit; num = Math. floor(num/10); } console.


2 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>
like image 90
vsync Avatar answered Oct 20 '22 01:10

vsync


Assuming @DominicTobias is correct, you can use this:

console.log( 
    +prompt("Enter a value").split("").reverse().join("") 
)
like image 36
Arg0n Avatar answered Oct 20 '22 00:10

Arg0n