# 9-line accepted Java code, without the need of handling overflow

• compare half of the digits in x, so don't need to deal with overflow.

``````public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}``````

• does the variable "rev" count as extra space?

• extra space usually means O(n) extra space.

• No extra space means O(1) extra space

• no extra space means anything of the order greater than O(1) .
Extra space would mean if the space can be expressed as a function of the length of the input. For eg. space could be O(n) if we store the n numbers while comparing arrays.

• excellent!!!

• you are genius!

• This post is deleted!

• The first if condition

``````if (x<0 || (x!=0 && x%10==0)) return false;
``````

should handle that.

• don't understand the last line "return (x==rev || x==rev/10);" why is rev/10? x==rev is not enough?

• Hi,your last line "return (x==rev || x==rev/10);",can you explain when x==rev?

• Hi guys. I just don't know why we need to concern the overflow. When the reversed number overflows, it will becomes negative number which will return false when compared with x.
Here is my AC code.

``````public class Solution {
public boolean isPalindrome(int x) {
if(x < 0) return false;
int y = x;
int res = 0;
while(y != 0) {
res = res * 10 + y % 10;
y /= 10;
}
return x == res;
}
}``````

• sorry,i see now.

• x==rev is for the scenery of even digits, x==rev/10 for the odd digits.

• Can anyone explain what the overflow problem is here?

• leetcode_damon is correct. The point is that x is changing.

• make a friend?→_→

• Haha, great idea! Overflow becomes a good thing :-)

• Overflow does not guarantee to be negative. Think about 2147483647 *3 is also positive.

• You used extra space when you define the variable int rev=0, no?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.