我编写了以下代码来反转JavaScript中的整数。它工作正常,但在输入-900000时返回0。有谁知道可能是错的吗?
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var negative_number= false;
var k;
var new_string;
if(x<0){
negative_number = true;
x=Math.abs(x);
}
var n = x.toString(); // convert from number to string
// Step 1. Use the split() method to return a new array
var splitString = n.split(""); // var splitString = "hello".split("");
// ["h", "e", "l", "l", "o"]
if (negative_number)
{
for (var i=0; i< splitString.length-1; i++)
{
splitString[i]=splitString[i+1];
}
}
// Step 2. Use the reverse() method to reverse the new created array
var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
// ["o", "l", "l", "e", "h"]
// Step 3. Use the join() method to join all elements of the array into a string
var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
// "olleh"
//return joinArray;
var number = Number(joinArray);
if (negative_number)
number= -Math.abs(number);
//Step 4. Return the reversed string
return number;
};
最佳答案
您无需从负数中去除-
符号,您已经将绝对值作为x
了。删除循环移动数字并破坏您的值的循环。