下面是我的源代码来反转(如在镜子中)给定的数字。我需要使用数组的反向方法来反转数字。
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);
下面是我的源代码来反转(如在镜子中)给定的数字。我需要使用数组的反向方法来反转数字。
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);
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") )
)
上面的代码使用按位运算符进行快速数学运算
这种方法比将数字转换为数组然后将其反转并再次加入的其他方法要快得多。这是一个低级的极速解决方案。
假设@DominicTobias 是正确的,你可以使用这个:
console.log(
+prompt("Enter a value").split("").reverse().join("")
)
最近有人问我如何解决这个问题,这是我最初的解决方案:
所需的输出: 123 => 321、-15 => -51、500 => 5
function revInt(num) {
// Use toString() to convert it into a String
// Use the split() method to return a new array: -123 => ['-', '1','2','3']
// Use the reverse() method to reverse the new created array: ['-', '1','2','3'] => ['3','2','1','-'];
// Use the join() method to join all elements of the array into a string
let val = num.toString().split('').reverse().join('');
// If the entered number was negative, then that '-' would be the last character in
// our newly created String, but we don't want that, instead what we want is
// for it to be the first one. So, this was the solution from the top of my head.
// The endsWith() method determines whether a string ends with the characters of a specified string
if (val.endsWith('-')) {
val = '-' + val;
return parseInt(val);
}
return parseInt(val);
}
console.log(revInt(-123));
一个更好的解决方案:
在我再三考虑之后,我想出了以下几点:
// Here we're converting the result of the same functions used in the above example to
// an Integer and multiplying it by the value returned from the Math.sign() function.
// NOTE: The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(-123));
注意:第二个解决方案更直接,恕我直言
或者,作为单行(x
包含要反转的整数):
revX=x.toFixed(0).split('').reverse().join('')-0;
该数字将被分成单独的数字,反转,然后再次重新组合成一个字符串。在-0
随后再次转换成一个数字。
这是我的解决方案,没有预定义功能的纯JS。
function reverseNum(number) {
var result = 0,
counter = 0;
for (i = number; i >= 1; i = i / 10 - (i % 10) * 0.1) {
counter = i % 10;
result = result * 10 + counter;
}
return result;
}
console.log(reverseNum(547793));