题目要求:
Determine whether an integer is a palindrome. Do this without extra space.
即判断一个数x是不是回文数
思路:
首先获取这个整数的位数count,定义一个n等于10的count-1次幂,让一个临时变量number等于这个整数。
number%10获取的是最后一位,x/n%10获取的是第一位,判断这两个值是否相等,不相等就返回false,相等就让number/10,n/10,
接下来比较的就会是第二位和倒数第二位,直到比较完最中间的一位为止。
public class Solution {
public boolean isPalindrome(int x)
{
//负数不是回文数
if(x<0)
{
return false;
}
//个位数是回文数
else if(x<10)
{
return true;
}
int count = count(x);
//获取一个n,等于10的count-1次幂
int n = (int) Math.pow(10,count-1);
int number = x;
for(int i=0;i<count/2;i++)
{
if(x/n%10==number%10)
{
n/=10;
number/=10;
}else{
return false;
}
}
return true;
}
//获取整数的位数
public int count(int x)
{
int count = 0;
while(x>0)
{
x/=10;
count++;
}
return count;
}
}