gpt4 book ai didi

javascript - JavaScript 中的 32 位整数是什么?

转载 作者:行者123 更新时间:2023-12-03 03:50:36 26 4
gpt4 key购买 nike

我正在做一些编码挑战,遇到了一些我不太熟悉的东西。我更好奇它是什么以及为什么它在那里。

提示非常简单:

Given a 32-bit signed integer, reverse digits of an integer.

Example:
Input: -123
Output: -321

Example:
Input: 120
Output: 21

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

我想出了这个。

var reverse = function(x) {
var isNegative = false;
if(x < 0){
isNegative = true;
x *= -1;
};
var reverseX = parseInt(String(x).split('').reverse((a,b) => a - b).join(''));
if(reverseX > Math.pow(2,32)){
return 0;
}
if(isNegative){
return -1 * reverseX
} else {
return reverseX;
}
};

但是,我对一些失败的测试感到困惑:

Input:
1563847412
Output:
2147483651
Expected: 0

据我了解,32位整数是2^32。它在 JS 中的意义是什么?如果我开始回顾会发生什么? (2^32 + 1)

我的第二个问题,如果我可以问两个的话,我是否“预期”如果 reverseX 的值超过 2^32,但它仍然未通过测试。

if (reverseX > Math.pow(2, 32)) {
return 0;
}

当我超过 32 位整数时,如何正确返回 0

最佳答案

有符号整数的上限不是 232 - 1,而是 231 - 1,因为第一位是符号位。

如果进行比较,您会发现测试给出了正确的结果。

请注意,JavaScript 使用 IEEE-754 floating point数字的表示,即使它们是整数。但浮点的精度足以对 32 位整数执行精确计算。正如您所意识到的,您需要进行必要的测试来检测 32 位溢出。

有关代码的一些注释:它将参数传递给 Array#reverse方法,这是一种不带参数的方法。这是我的编写方式——请参阅代码中的注释:

// Name argument n instead of x, as that latter is commonly used for decimal numbers 
function reverse(n) {
// Array#reverse method takes no argument.
// You can use `Math.abs()` instead of changing the sign if negative.
// Conversion of string to number can be done with unary plus operator.
var reverseN = +String(Math.abs(n)).split('').reverse().join('');
// Use a number constant instead of calculating the power
if (reverseN > 0x7FFFFFFF) {
return 0;
}
// As we did not change the sign, you can do without the boolean isNegative.
// Don't multiply with -1, just use the unary minus operator.
// The ternary operator might interest you as well (you could even use it
// to combine the above return into one return statement)
return n < 0 ? -reverseN : reverseN;
}

console.log(reverse(-123));
console.log(reverse(1563847412));

更高效

与简单的算术运算相比,转换为字符串、拆分和连接是相对昂贵的操作。因此,解决这样的问题会更节省时间(和内存):

function reverse(n) {
var reverseN = 0;
var sign = n < 0;
n = Math.abs(n);
while (n) {
reverseN = reverseN*10 + (n % 10);
n = Math.floor(n/10);
}
return reverseN > 0x7FFFFFFF ? 0 : sign ? -reverseN : reverseN;
}

console.log(reverse(-123));
console.log(reverse(1563847412));

关于javascript - JavaScript 中的 32 位整数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47600096/

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