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.
The topic detects whether an integer is a palindrome integer, such as 12321 is a palindrome integer.
Class Solution {public: bool Ispalindrome (int x) { if (x < 0) return false; int reverse = 0; int power = 1; while (X/POWER/10) { power *=; Reverse = reverse * + x/power%10; } return x%power = = reverse; }};
My idea is to use reverse number, plus the proper handling of overflow.
The feeling is still relatively new and original.
The following is a collection of online blog common wording for everyone to compare:
Method One:
Class Solution {public: bool Ispalindrome (int x) { //Start Typing your C + + solution below //do not write I NT Main () function if (x < 0) return false; int div = 1; while (X/10 >= div) { //Get large Division div *=; } while (x > 9) { int. = X/div; Left digit int low = x%; Right digit if (high! = Low) {return false; } x = (x% div)/ten; Get number between first and last div/=; } return true; }};
Method Two (source):
Class Solution {public: bool Check (int x, int &y) { if (x = = 0) return true; if (check (X/10, y) && (x%10 = = y%10)) { y/=; return true; } else { return false; } } BOOL Ispalindrome (int x) { //Start Typing your C + + solution below //do not write int main () function if (x < 0) return false; return check (x, x);} ;
The second method is more characteristic. But strictly speaking, it does not meet the requirements of the topic. The title requirement is not to use the auxiliary space.
Palindrome number--Leetcode