Determine whether an integer is a palindrome. Do the without extra space. (Do not use additional spaces)
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.
Analysis:
Palindrome number, and the topic requires that no extra space can be used.
That is, you cannot use a palindrome string method.
The subject is very simple, calculate the inverse of x A, compare a and X is equal to the line.
1 classSolution {2 Public:3 BOOLIspalindrome (intx) {4 //figure out the inverse of x a, and compare whether a is equal to X .5 intA =0, B =x;6 while(B >0){7A = A *Ten+ b%Ten;8b/=Ten;9 }Ten if(A = =x) One return true; A Else - return false; - the } -};
Other code on the net, its idea: each time to extract the head and tail two number, judge whether they are equal, judge to turn tail two number
1 classSolution {2 Public:3 BOOLIspalindrome (intx) {4 5 //Negative number6 if(X <0)7 return false;8 9 intLen =1;Ten while(X/len >=Ten) OneLen *=Ten; A - while(X >0) { - the //get the head and tail number - intleft = x/Len; - intright = x%Ten; - + if(Left! =Right ) - return false; + Else { A //remove the head and tail number atx = (x% len)/Ten; -Len/= -; - } - } - - return true; in } -};
Leetcode 9. Palindrome number (judging palindrome numbers)