Home » Java » Leetcode ninth question - Palindrome Number

Leetcode ninth question - Palindrome Number


Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes (ie, -1)


If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case


subject requirements can not use extra storage space, generally need to use recursion. Notice: negative is not a palindrome, if the integer is converted to a string, pay attention to the use of extra storage space, if you try to turn an integer, it will encounter may overflow after flip. The author use the judgment method of high and low is the same, only need to define a count variable can be achieved without occupying additional storage space. In addition to using for instead of while circulation cycle, because the running time is relatively shorter.


class Solution (object):
Def isPalindrome (self, X):
Type: x: int
Rtype:: bool
If (x < 0) | (x = 0x7FFFFFFF):
Return False
I = 1
Temp = x/10
While (temp > 0):
Temp / = 10
I = 1
# know how many, the most high cycle is equal to the lowest judgment
For I in range (i-1,0, -2):
Base = pow (10, I)
If (x/base = x%10):
X = (x%base) /10
Return False
Return True


public class {Solution
Public Boolean isPalindrome (int x) {
Int i, base;
If (x < 0 || x = = 0x7FFFFFFF) return false;
Look at the number of how many / /;
For (I = 1; x/ (int) Math.pow (10, I) > 0; i++);
For (i--; i>0; I = 2) {
Base = (int) Math.pow (10, I);
If (x/base = = x%10) {
The most high with the highest / equal, then remove the high and low position and the next cycle;
X = (x%base) /10;
Else return false;
Return true;