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.
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int t = x;
int l = 0;
int rest = 0;
//get the length of x
while (t != 0) {
t = t / 10;
l++;
}
int times = l / 2;
while (times > 0) {
rest = x % 10;
x = (x - (rest + rest * (int) (Math.pow(10, (l - 1)))));
if ((x < 0) || (x % 10) != 0) {
return false;
}
x = x / 10;
l -= 2;
times--;
}
if (l % 2 == 0) {
if (x == 0) {
return true;
}
} else {
if ((0 <= x) && (x < 10)) {
return true;
}
}
return false;
}
}
看了别人写的 比我的思路清楚多了
public class Solution {
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0) return false;
int length=1;
int tempX=x;
while(tempX/10!=0)
{
length*=10;
tempX=tempX/10;
}
/*
old strategy will cause overflow:
int d=1;
while(x/d!=0)
{
d*=10;
}
d/=10;
*/
while(x!=0)
{
int left=x/length;
int right=x%10;
if(left!=right) return false;
x=(x-left*length)/10;
length/=100;
}
return true;
}
}
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0) return false;
int length=1;
int tempX=x;
while(tempX/10!=0)
{
length*=10;
tempX=tempX/10;
}
/*
old strategy will cause overflow:
int d=1;
while(x/d!=0)
{
d*=10;
}
d/=10;
*/
while(x!=0)
{
int left=x/length;
int right=x%10;
if(left!=right) return false;
x=(x-left*length)/10;
length/=100;
}
return true;
}
}
本文提供了一种不使用额外空间的方法来判断整数是否为回文数,包括处理负数和溢出情况。
375

被折叠的 条评论
为什么被折叠?



