问题描述:
Determine whether an integer is a palindrome. Do thiswithout extra space.
click to showspoilers.
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 youhave solved the problem "Reverse Integer", you know that the reversedinteger 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) { //特殊值判断 if(x < 0) return false; if(x < 10)//只有一位 return true; //计算x的10进制长度 int temp = x; int left_base = 1; int right_base = 1; while((temp /= 10) != 0) { left_base *= 10; } while(left_base > right_base) { //相应位进行比较即可 if((x / left_base % 10) != (x / right_base % 10)) { return false; } left_base /= 10; right_base *= 10; } return true; } public static void main(String[] args) { int x = 12; System.out.println(new Solution().isPalindrome(x)); } }