原题网址:https://leetcode.com/problems/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.
方法一:使用pow方法和log方法,性能较低。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
for(int i=(int)(Math.log(x)/Math.log(10)); i>0; i-=2) {
if (x / (int)Math.pow(10, i) != x % 10) return false;
x = (x - x / (int)Math.pow(10, i) * (int)Math.pow(10, i)) / 10;
}
return true;
}
}
方法二:自己模拟pow方法和log方法。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int pow = 1;
while (x / pow >= 10) pow *= 10;
while (x>0) {
int hd = x / pow ;
int ld = x % 10;
if (hd != ld) return false;
x = (x - hd * pow) / 10;
pow /= 100;
}
return true;
}
}