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 is thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you had solved the problem "Reverse integer", you know that the reversed integer might overflow. How do would handle such case?
There is a more generic the solving this problem.
A very concise C + + solution:
Only half of the palindrome is compared.
Public Boolean isPalindrome1(intx) {if(x = =0)return true;//In Leetcode, negative numbers and numbers with ending zeros // is not palindrome if(X <0|| X%Ten==0)return false;//Reverse half of the number //The exit condition is y >= x //So, overflow is avoided. inty =0; while(Y < x) {y = y *Ten+ (x%Ten);if(x = = y)//To check numbers with odd digits return true; X/=Ten; }returnx = = y;//To check numbers with even digits}
The solution for Python should be a comparison of before and after:
class solution: # @param x, an integer # @return A Boolean def ispalindrome(self, x): ifX <0:return FalseRanger =1 whileX/ranger >=Ten: Ranger *=Ten whileX:left = X/ranger right = x%Ten ifLeft! = Right:return Falsex = (x% Ranger)/TenRanger/= - return True
The solution to the Python string:
class Solution: # @param {integer} x # @return {boolean} def isPalindrome(self, x): return str(x)==str(x)[::-1]
Leetcode 9 palindrome Number palindrome