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.
Subscribe to see which companies asked this question
Solution 1: The first thing to think about is to convert an integer to a string, and then compare it from both ends to the middle. Or each will be taken out after the temporary storage and comparison. But this requires extra space.
classSolution { Public: BOOLIspalindrome (intx) {if(X <0)return false; strings =to_string (x); inti =0, j = s.size ()-1; while(I <j)if(s[i++]! = s[j--]) return false; return true; }};
Solution 2: You can find a way to take out the highest and lowest digits of the integer each time to compare, and then remove this highest and lowest bit, take the new whole number of the lowest bit and the highest bit comparison ...
classSolution { Public: BOOLIspalindrome (intx) {if(X <0)return false; intnum = x, n =0; while(Num >0) { ++N; Num/=Ten; } if(n = =1)return true; inti =1, j = n-1; while(I <=j) {intLow = x% (int) Pow (Ten, i)/(int) Pow (TenI1); intHigh = x/(int) Pow (Ten, j)%Ten; if(Low! = high)return false; ++i; --J; } return true; }};
A simpler way of writing, in strict accordance with the above ideas:
classSolution { Public: BOOLIspalindrome (intx) {if(X <0)return false; intn =1; while(x/n >=Ten) n *=Ten; while(X >0) { intLow = x%Ten; intHigh = x/N; if(Low! = high)return false; X= (x% n)/Ten;//Take out the remaining number in the middle.N/= -;//Note that two bits are removed each time, so the divisor shrinks by 100 times times. } return true; }};
[Leetcode]68. Palindrome number palindrome digit