判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
package LeetCode;
public class A9回文数 {
public boolean isPalindrome(int x) {
int num = x; // 备份x
if (x < 0) {
return false;
} else if (x <= 9) {
return true;
} else {
int length = 0;
while (x != 0) { // 计算整数的位数
length++;
x /= 10;
}
// System.out.println(length); // 输出整数的位数
for (int i = 0; i < length / 2; i++) { // 不管奇偶都是一样的
if (theNumOf(num, i, length) != theNumOf(num, length - 1 - i, length)) {
return false;
}
}
}
return true;
}
private int theNumOf(int num, int i, int length) {
// TODO Auto-generated method stub
// System.out.println((int) (num / Math.pow(10, length - 1 - i) % 10));
return (int) (num / Math.pow(10, length - 1 - i) % 10);
}
public static void main(String[] args) {
A9回文数 a9回文数 = new A9回文数();
int x = 20;
// int x = 1000030001;
System.out.println(a9回文数.isPalindrome(x));
}
}