Java [leetcode 9] Palindrome Number

时间:2022-11-04 05:13:31

问题描述:

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

解题思路:

首先判断是否为负数,若是负数,直接返回false。否则继续下面判断:

从两头开始往中间读数,分别判断即可。

代码如下:

public class Solution {
public boolean isPalindrome(int x) {
int divisor = 1;
int left;
int right;
int temp = x;
if (x < 0)
return false;
while (temp / 10 > 0) {
divisor *= 10;
temp = temp / 10;
} while (x != 0) {
left = x / divisor;
right = x % 10;
if (left != right)
return false;
x = (x % divisor) / 10;
divisor = divisor / 100;
}
return true;
}
}