题目:
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.
得到第一个数:x / 10^(length -1-i), 最后一个数:x % 10^(length-1-i) - x % 10^(length - 1- i) / 10 * 10
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
int length = 0;
int y = x;
while( y != 0) {
length++;
y /= 10;
}
for(int i = 0; i < length / 2; i++) {
if(x / (int)pow(10.0, (double)(length - 2 * i - 1)) != x % 10)
return false;
x = x % (int)pow(10.0, (double)(length - 2 * i - 1)) / 10;
}
return true;
}
};
Java 版:
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0)
return false;
int length = 0, y = x;
while(y != 0) {
length += 1;
y /= 10;
}
for(int i = 0; i < length / 2; i++) {
if(x / (int)Math.pow(10, length - i * 2 - 1) != x % 10)
return false;
x = x % (int)Math.pow(10, length - i * 2 - 1) / 10;
}
return true;
}
}
Python 版:
class Solution:
# @return a boolean
def isPalindrome(self, x):
length = 0
if x < 0:
return False
y = abs(x)
while y != 0:
y = y / 10
length += 1
for i in range(0, length/2):
if abs(x) / (10 ** (length - 1 - 2 * i)) != abs(x) % 10:
return False
x = abs(x) % (10 ** (length - 1 - 2 * i)) / 10
return True
本文介绍了一种不使用额外空间判断整数是否为回文数的方法,并提供了C++、Java及Python三种语言的实现代码。
274

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



