您的位置:首页 > 编程语言 > Java开发

Leetcode刷题记——9. Palindrome Number(回文数字)

2016-10-09 17:52 387 查看
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: transparent;">一、题目叙述:</span>

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

click to show spoilers.

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.

Subscribe to see which companies asked this question

二、解题思路:

这题挺简单,但我依旧写的非常复杂,代码能力还是很弱,在网上搜了下人家的代码,简洁哭,等会把人家源码也一起贴出来。

1、负数不算是回文

三、源源源码:

1、我的烂码。

public class Solution
{
public boolean isPalindrome(int x)
{
boolean isPal = true;
int temp = x;
int count = 0;
if (temp < 0) return false;
while (temp != 0)
{
temp = temp / 10;
count ++;
}
if (x == 0) return true;
for (int i = 0; i < count / 2; i++)
{
temp = x;
int left = 1;
for (int j = 0; j < i; j++ )
left = left * 10;
left = temp / left;
left = left % 10;
temp = x;
int right = 1;
for (int j = 0; j < count - 1 - i; j++)
right = right * 10;
right = temp / right;
right = right % 10;
if (left != right) {isPal = false; break;}

}
return isPal;
}
public static void main(String args[])
{
int s = 1;
Solution a = new Solution();
System.out.println(a.isPalindrome(s));
}
}2、搜的简洁代码

bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java