JavaScript:如何反转数字? [英] JavaScript: How to reverse a number?

查看:68
本文介绍了JavaScript:如何反转数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的源代码,用于反转给定的数字(如镜像所示). 我需要使用数组的反向方法来反转数字.

Below is my source code to reverse (as in mirror) the given number. I need to reverse the number using 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);

推荐答案

保持类型number,不使用任何高级函数:

Keeping the type number, without any high-order function:

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") ) 
)

以上代码使用按位运算符快速数学

此方法比将数字转换为数组然后反转并重新加入的其他方法 更快 .这是一个低级的快速解决方案.

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 &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>

这篇关于JavaScript:如何反转数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆