Q:
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.
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.
A:
下面是用了extra space的解法。public class PalindromeNumber { public boolean isPalindrome(int x) { if (x < 0) return false; int div = 1; while (x / div >= 10) { div *= 10; } while (x != 0) { int l = x / div; int r = x % 10; if (l != r) return false; x = (x % div) / 10; div /= 100; } return true; } }
------------第二遍-------方法一的实现----------
public class Solution { public boolean isPalindrome(int x) { if(x<0) return false; long n10s = 1; while(x> n10s*10 ){ n10s *= 10; } while(x !=0){ if(x%10 != x/n10s){ return false; }else{ x = (int) (x % n10s); n10s /=100; x = x/10; } } return true; } }
Here, on line 5, as we use * to do comparison. ----> if declaring
int n10s = 1; would requrire n10s > Integer.MAX_VALUE; which is a bug.
so, we 'd better check the division with 10; LOL
%%%%%%%%%既然不让用extra space, 那就只能用Stack来存储喽%%%%%%%%
public class Solution { public boolean isPalindrome(int x) { return x>=0 && helper(x, (int)Math.pow(10,getLen(x)-1)); } private boolean helper(int x, int pow10){ return x==0 || ( (x%10 == x/pow10) && helper( (x%pow10) /10, pow10/100) ); } private int getLen(int x){ return x==0? 0 : 1+getLen(x/10); } }
No comments:
Post a Comment