Palindrome Number
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.
注意是十进制的比较,所以不能用位运算。
1 public class Solution { 2 public boolean isPalindrome(int x) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(x < 0) return false; 5 int len = 0; 6 int xx = x; 7 while(xx > 0){ 8 len ++; 9 xx = xx / 10; 10 } 11 for(int i = 0; i < len / 2; i ++){ 12 int a = (x / (int)Math.pow(10, i)) % 10; 13 int b = (x / (int)Math.pow(10, len - i - 1)) % 10; 14 if(a != b) return false; 15 } 16 return true; 17 } 18 }
posted on 2013-10-17 13:49 Step-BY-Step 阅读(136) 评论(0) 编辑 收藏 举报