下面是我用来反转(就像在镜像中)给定数字的源代码。我需要使用数组的反转方法来反转数字。
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);发布于 2018-09-17 19:05:22
低级整数反转:
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 × 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>
发布于 2016-06-27 20:20:42
假设@DominicTobias是正确的,你可以使用:
console.log(
+prompt("Enter a value").split("").reverse().join("")
)
发布于 2018-06-30 00:34:35
或者,作为一行程序( x包含要反转的整数):
revX=x.toFixed(0).split('').reverse().join('')-0;数字将被分成单独的数字,颠倒过来,然后重新组合成一个字符串。然后,-0再次将其转换为数字。
https://stackoverflow.com/questions/38053729
复制相似问题