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);
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.
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.
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 × 10')
await delay()
printLine('1.2 →', 30)
await delay()
printLine(1, 32)
await delay()
printLine(1, '32 × 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>
Assuming @DominicTobias is correct, you can use this:
console.log(
+prompt("Enter a value").split("").reverse().join("")
)
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