回文数
题目:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
思路:
跟整数反转很像,如果是负数直接返回false;如果不是把整数反转过来跟输入参数比较是不是相等的即可。
package cn.itcast.day06.demo01;
public class isPalindrome {
public static void main(String[] args) {
Solution3 method = new Solution3();
boolean re=method.isPalindrome(10);
System.out.println("结果是: "+re);
}
}
class Solution3 {
public boolean isPalindrome(int x) {
if(x<0){
return false;
}
int res=0;
int tmp=x;
while(tmp!=0){
int t=tmp%10;
int newres=res*10+t;
tmp=tmp/10;
res=newres;
}
if (res==x){
return true;
}else{
return false;
}
}
};