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 notable place is without extra space.
The code is as follows:
BOOLIspalindrome (intx) {if(x<0) return false; for(intI=1; x>=Ten; i++) { intFirst =x,last=x; intj=0, k=0; Last= x percentTen; for(j=0; first>=Ten; j + +) { First=first/Ten; } if(First! =Last )return false; for(k=0; k<j;k++) { First= first*Ten; } x= (X-first)/Ten; if(x==0) return true; First=x; for(k=0; first>=Ten; k++) First= first/Ten; J= j-k-2; if(j!=0) { if(x<Ten) return false; for(k=0; k<j;k++) { inttmp=x%Ten; if(tmp!=0) return false; X=x/Ten; } } } return true;}
View Code
Feel like this is very messy, so to see others write. Find the same idea, take the first two numbers at a time, and judge whether they are the same.
Give someone else's code:
BOOLIsPalindrome2 (intx) {//Negative number if(X <0) return false; intLen =1; while(X/len >=Ten) Len*=Ten; while(X >0) { //get the head and tail number intleft = x/Len; intright = x%Ten; if(Left! =Right )return false; Else { //remove the head and tail numberx = (x% len)/Ten; Len/= -; } } return true;}
View Code
The same way of thinking, seems to be more ingenious than mine ah.
Leetcode "9" palindrome number