LeetCode 7:反向整数|为什么它可以长期使用,但不能与INT一起使用?
我试图解决 this leetcode上的问题,您必须在其中使用一个功能来反向integer逆转函数。约束是,如果相反的数字超出了签名的32位整数范围,即(-2^31)to(2^31-1),则您返回0。当我使用整数使用整数时,如此
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return rev;
}
}
Intellijijij想法表明,但是
Condition 'rev > Integer.MAX_VALUE' is always 'false'
,当我使用长时间而不是INT时,问题就可以解决,并且该程序可以按照您的期望工作。
class Solution {
public int reverse(int x) {
long rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return (int)rev;
}
}
我想知道为什么会这样?
I was trying to solve this problem on LeetCode where you have to reverse an integer using a function. The constraint is that if the reversed number goes outside the signed 32-bit integer range, i.e. (-2^31) to (2^31 - 1) then you return 0. When I use an integer for the reversed variable like this
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return rev;
}
}
IntelliJ IDEA shows that the
Condition 'rev > Integer.MAX_VALUE' is always 'false'
However, when I use a long instead of int, the problem is resolved and the program works as you would expect.
class Solution {
public int reverse(int x) {
long rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return (int)rev;
}
}
I was wondering why is that the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在第一个代码块中,
rev
是整数。因此,它不可能比integer.max_value
- 整数的最大值更大。使用
长
,可以具有大于最大可能int
值的值。 Javaint
是签名的32位值。 Java长
是签名的64位值。In the first code block,
rev
is an integer. Thus, it is impossible for it to be greater thanInteger.MAX_VALUE
- the maximum value for an integer.With a
long
, it is possible to have a value greater than the greatest possibleint
value. A Javaint
is a signed 32-bit value. A Javalong
is a signed 64-bit value.对我来说,这有效...
For me this works...
使用Python 3格式在LeetCode上尝试此代码。
Try this code Using Python 3 format at Leetcode you will passed..
在Java中,INT数据类型是一个32位签名的整数,这意味着它可以将值保持在-2,147,483,648到2,147,483,647。如果REV超过此范围,它将溢出并缠绕到最低值,即-2,147,483,648。因此,条件Rev&gt; integer.max_value永远不会是正确的。
In Java, the int data type is a 32-bit signed integer, which means it can hold values from -2,147,483,648 to 2,147,483,647. If rev exceeds this range, it will overflow and wrap around to the minimum value, which is -2,147,483,648. Therefore, the condition rev > Integer.MAX_VALUE will never be true.