gpt4 book ai didi

JavaScript:如何反转数字?

转载 作者:行者123 更新时间:2023-12-01 07:09:37 27 4
gpt4 key购买 nike

下面是我的源代码来反转(如在镜子中)给定的数字。
我需要使用数组的反转方法来反转数字。

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

最佳答案

低级整数反转:

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

以上代码使用 bitwise operators快速数学
这个方法是 更快与将数字转换为数组然后将其反转并再次加入它的其他方法相比。这是一个低级的极速解决方案。
插图表:

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:如何反转数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38053729/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com