题目:
判断一个整数是否是回文数?回文数是指正序和倒序为一样的
示例;
121 121 true
-121 121- false
10 01 false
思路:
第一步:判断是否小于0,若小于0直接判断为false
第二步:若大于0,将其进行整数的反转后比较与反转前是否相等即可判断其是否为回文数。
public class Id09Palindrome {
public static void main(String[] args) {
Id09Palindrome palindrome = new Id09Palindrome();
System.out.println(palindrome.isPalindrome(2147483647));
}
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int size = String.valueOf(x).length();
int factor;
if (size == 1) {
return true;
} else {
factor = (int) Math.pow(10, size - 1) + 1;
}
//98 908 302 1000
if ((x + 1) % factor == 0) return false;
int result = x % factor;
int resultSizeLimit = getResultLimit(size);
if (result != 0) {
if (result % 10 != 0
|| result < resultSizeLimit) {
return false;
} else {
x = division(result);
}
} else {
return true;
}
return isPalindrome(x);
}
/**
* 余数限制 100030001 余数30000>10000 限制 1000021
*
* @return
*/
private int getResultLimit(int size) {
if (size % 2 == 0) {
return (int) Math.pow(10, size / 2);
} else {
return (int) Math.pow(10, (size - 1) / 2);
}
}
/**
* make 330000->33
*
* @param x
* @return
*/
private int division(int x) {
for (int i = String.valueOf(x).length(); i > 0; i--) {
int tmp = (int) Math.pow(10, i - 1);
if (x % tmp == 0) {
return x / tmp;
}
}
return 0;
}
}