leetcode-9-easy
回文数
思路一: 暴力求解,把数字一个一个拆分,放队列里面,最后取队列的首尾,对比是否相同
public static boolean isPalindrome2(int x) {
if (x < 0) return false;
if (x < 10) return true;
Deque<Integer> queue = new ArrayDeque<>();
while (x > 0) {
queue.offer(x % 10);
x /= 10;
}
while (queue.size() >= 2) {
Integer first = queue.pollFirst();
Integer last = queue.pollLast();
if (!first.equals(last)) {
return false;
}
}
return true;
}
思路二: 将数字翻转,对比翻转后的数字和原数字是否一致。有溢出问题,虽然 32 位整数里面不存在一个正非回文数溢出后等于原数
public static boolean isPalindrome(int x) {
if (x < 0) return false;
if (x < 10) return true;
int ori = x;
int t = x % 10;
x /= 10;
while (x > 0) {
t = t * 10 + x % 10;
x /= 10;
}
return ori == t;
}
思路三: 溢出优化,翻转一半,怎样确定一半?当求解的 x 剩余部分小于或者等于翻转数字时,说明已经在一半了,跳出循环,最后判断两数是否相等,奇数位数只需要把数字去一位
public static boolean isPalindrome(int x) {
if (x < 0) return false;
if (x < 10) return true;
int t = x % 10;
x /= 10;
while (x > t) {
t = t * 10 + x % 10;
x /= 10;
}
return x == t || x == t / 10;
}

浙公网安备 33010602011771号