题目描述:
Determine whether an integer is a palindrome. An integer is a
palindrome when it reads the same backward as forward.Follow up:
Coud you solve it without converting the integer to a string?
解题思路:
方法一:
step1:若该整数为负,则必不是回文数字
step2:若该整数位0,则必为回文数字
step3:在该整数为正数的情况下,将每一位数字按顺序存储在数组里,若为回文,则必满足镜像对称.
时间复杂度为O(n)(n为x的位数)
代码如下:
class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
if(x==0) return true;
int[] p = new int[];
int i=0;
while(x!=0){
p[i++]=x%10;
x/=10;
}
for(int j=0;j<(i+1)/2;j++){
if(p[j]!=p[i-j-1]) return false;
}
return true;
}
}
方法二:
借助一个反向整数来验证。
step1:如果该整数为负或非零但末位为零,则必不是回文数字。
step2:从低位到高位构建该整数的反向整数,直到反向整数的位数为原数字的一半(偶数位)或一半+1(基数位),同时舍弃x的低位。若x与反向数组相等,则为回文数字。
代码如下:
class Solution {
public boolean isPalindrome(int x) {
if(x<0||(x%10==0&&x!=0)) return false;
int rev = 0;
while(x>rev){
rev=rev*10+x%10;
x/=10;
}
return x==rev||x==rev/10;
}
}