题目描述
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
解题思路
1、纯数学最笨的方法,把数字掰成两半再对比。
class Solution {
public boolean isPalindrome(int x) {
int temp=x,i=0,left,right=0;
boolean result;
if(x<0){
//x<0一定不是回文数,直接排除
result = false;
}else{
//检查x的长度,以找到数字x的中位的位数
while(temp != 0){
temp = temp/10;
i++;
}
//左侧直接利用除法截取左半段整数
temp = x;
left = temp/(int)Math.pow(10, i/2);
//右侧存在x长度奇偶的问题,为了保证右侧截取的长度和左侧一致,判断i的奇偶并处理
i = i%2==0?i/2:i/2+1;
temp = x;
//类似于题目2整数反转的方法,将右侧数字倒置检验
for(;i>0;i--){
right = right*10 + temp%10;
temp = temp/10;
}
result = left==right?true:false;
}
return result;
}
}
2、纯数学方法,聪明一点,直接把整数倒置后和原整数对比即可。
class Solution {
public boolean isPalindrome(int x) {
int temp=x,invert=0;
boolean result;
if(x<0){
result = false;}
else{
while(temp != 0){
invert = invert*10 + temp%10;
temp = temp/10;
}
result = (x == invert);
}
return result;
}
}
3、把第二个方法化简一下,还可以这么写。
class Solution {
public boolean isPalindrome(int x) {
int t=x,i=0;
boolean result;
if(x<0)return false;
for(;t!=0;i=i*10+t%10,t=t/10);
return x==i;
}
}
4、利用字符数组对撞
补充个知识点,关于java中,整数=>字符串,字符串=>字符数组,字符数组=>字符串
int x = 123;
String[] str = Integer.toString(x); //整数转换为字符串
String strStringType="my string"; //创建一个字符串变量strStringType
char[] chrCharArray; //创建一个字符数组chrCharArray
chrCharArray = strStringType.toCharArray(); //将字符串变量转换为字符数组
strStringType= String.valueOf(chrCharArray ); //将字符数组转换为字符串
第四种方法的题解:
class Solution {
public boolean isPalindrome(int x) {
boolean result = true;
String str = Integer.toString(x); //将整数x转换为字符串
char t[] = str.toCharArray(); //将字符串转换为字符数组
for(int r = t.length-1,l = 0; l<r; r--, l++)
if(t[l] != t[r])result = false; //如果存在不对称的情况,返回false
return result;
}
}