下面是我的源代码,用于反转(如镜像中)给定的数字。 我需要使用反向数组方法来反转数字。
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);
答案 0 :(得分:5)
假设@DominicTobias是正确的,您可以使用:
console.log(
+prompt("Enter a value").split("").reverse().join("")
)
答案 1 :(得分:2)
或者,作为单行代码(x
包含要求逆的整数):
revX=x.toFixed(0).split('').reverse().join('')-0;
该数字将被分隔成各个数字,取反后再重新组合为一个字符串。 -0
然后将其再次转换为数字。
答案 2 :(得分:1)
function flipInt(n){
var digit, result = 0;
while( n ){
digit = n % 10; // get last digit. 123/10 -> 12.3 -> 3
result = (result * 10) + digit; // 123 -> 1230 + 4 => 1234
n = n/10|0; // remove last digit. 123 -> 12.3 -> 12
}
return result;
}
alert(
"Reverse number: " + flipInt( +prompt("Enter a value") )
)
我制作了jsperf test来比较上面的代码和另一个答案的代码,该代码将数字转换为字符串,然后将其转换为数组,然后将其反转,然后将其转换为字符串,然后再次为数字,然后我的代码运行~140x
更快
答案 3 :(得分:1)
最近有人问我如何解决此问题,这是我最初的解决方法:
所需的输出: 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));
注意:第二种解决方案更加简单,恕我直言
答案 4 :(得分:1)
这是我的解决方案,没有预定义函数的纯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));
答案 5 :(得分:0)
首先,我认为您不使用数组来存储数字。您正在使用java脚本变量。
试试这段代码,看看它是否有效。
var a = prompt("Enter a value");
var z = a;
var reverse = 0;
while(z > 0)
{
var digit = z % 10;
reverse = (reverse * 10) + digit;
z = parseInt(z / 10);
}
alert("reverse = " + reverse);
答案 6 :(得分:0)
使用JavaScript reverse()
数组方法可以反转数组元素的顺序。
var a = prompt("Enter a value");
var arr = [];
for (var i = 0; i < a.length; i++) {
arr[i] = a.charAt(i);
}
arr.reverse();
alert(arr);
&#13;
答案 7 :(得分:0)
我的反向字符串解决方案:
var text = ""
var i = 0
var array = ["1", "2", "3"]
var number = array.length
var arrayFinal = []
for (i = 0; i < array.length; i++) {
text = array[number - 1]
arrayFinal.push(text)
text = ""
number = number - 1
}
console.log(arrayFinal)
希望有帮助!
答案 8 :(得分:0)
假设您可能想将其反转为真数字而不是字符串,请尝试以下操作:
function reverseNumber(num){
num = num + '';
let reversedText = num.split('').reverse().join('');
let reversedNumber = parseInt(reversedText, 10);
console.log("reversed number: ", reversedNumber);
return reversedNumber;
}
答案 9 :(得分:0)
使用JavaScript reverse()和Math.sign()可以反转正负数。
var enteredNum = prompt("Enter integer");
function reverseInteger(enteredNum) {
const reveredNumber = enteredNum.toString().split('').reverse().join('');
return parseInt(reveredNumber)*Math.sign(enteredNum);
}
alert(reverseInteger(enteredNum));
答案 10 :(得分:0)
在纸上应用倒数逻辑并尝试,并且您必须关心除法,因为它提供浮点值,这就是为什么我们必须使用parseInt()的原因。
<head>
<script>
function palindrome()
{
var a = document.getElementById('str').value;
var r=0 ,t=0;
while(a>0){
r=a%10;
t=t*10+r;
a=parseInt(a/10);
}
document.write(t);
}
</script>
</head>
<body>
<form>
<input type="text" id="str"/>
<input type="submit" onClick="palindrome()" />
<form>
</body>
</html>
答案 11 :(得分:0)
function add( num:number){ //159
let d : number;
let a : number =0;
while(num > 0){ //159 15 1
d = num % 10;
a = a * 10 + d; //9 95 951
num = Math.floor(num/10); // 15 1 0
}
return a; //951
}
console.log(add(159));
答案 12 :(得分:0)
使用递归方法反转数字而不将其转换为字符串。
const num = 4578;
const by10 = (num) => {
return Math.floor(num / 10);
};
const remBy10 = (num) => {
return Math.floor(num % 10);
};
const reverseNum = (num, str = "") => {
if (num.toString().length == 1) return (str += num);
return reverseNum(by10(num), (str += remBy10(num)));
};
console.log(reverseNum(num, ""));
答案 13 :(得分:0)
var reverse = function(x) {
if (x > 2147483647 || x < -2147483648 || x === 0) {
return 0;
}
let isNegative = false;
if(x < 0){
isNegative = true;
x = -x;
}
const length = parseInt(Math.log10(x));
let final = 0;
let digit = x;
let mul = 0;
for(let i = length ; i >= 0; i--){
digit = parseInt(x / (10**i));
mul = 10**(length-i);
final = final + digit * mul;
x = parseInt(x % 10**i);
}
if (final > 2147483647 || final < -2147483648 ) {
return 0;
}
if(isNegative){
return -final;
}
else{
return final;
}
};
console.log(reverse(1534236469));
console.log(reverse(-123));
console.log(reverse(120));
console.log(reverse(0));
console.log(reverse(2,147,483,648));
答案 14 :(得分:-1)
甜美而简单:
function reverseNumber(num){
return parseInt(num.toString().split("").reverse().join(""));
}
答案 15 :(得分:-1)
以上代码不适用于负数。相反,请使用以下内容:
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
return ((x>=0) ? ((x==(x = parseInt(x.toString().split("").reverse().join("")))) ? true:false) : false);
};