Created
March 15, 2013 22:28
-
-
Save daifu/5173645 to your computer and use it in GitHub Desktop.
Determine whether an integer is a palindrome. Do this without extra space.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Determine whether an integer is a palindrome. Do this without extra space. | |
| Some hints: | |
| Could negative integers be palindromes? (ie, -1) | |
| If you are thinking of converting the integer to string, note the restriction of using extra space. | |
| You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? | |
| There is a more generic way of solving this problem. | |
| */ | |
| public class Solution { | |
| public boolean isPalindrome(int x) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if(x < 0) { | |
| // non negative number | |
| return false; | |
| } | |
| // check how many digit for x | |
| int digit = 0; | |
| int tmp = x; | |
| while(tmp > 0) { | |
| digit++; | |
| tmp /= 10; | |
| } | |
| int leftMostDigit = digit - 1; | |
| while(x > 0) { | |
| int mask = (int)Math.pow((double)10, (double)leftMostDigit); | |
| int leftVal = x / mask; | |
| int rightVal = x % 10; | |
| if(leftVal != rightVal) { | |
| return false; | |
| } | |
| x -= mask * leftVal; | |
| x /= 10; | |
| leftMostDigit -= 2; | |
| } | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment