Java [leetcode 9] Palindrome Number

问题描述:

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;
}
}
上一篇:lintcode.177 把排序数组转换为高度最小的二叉搜索树


下一篇:查看Linux服务器网络状态