题目:Determine whether an integer is a palindrome. Do this without extra space.
转成字符串,使用额外空间的解法。注意-123321应返回false
public boolean isPalindrome(int x) {
String string = ""+x;
for(int i=0;i<string.length()/2;i++) {
if(string.charAt(i)!=string.charAt(string.length()-i-1)) {
return false;
}
}
return true;
}
不用额外空间的解法,参考;
public class Solution {
public bool IsPalindrome(int x) {
// Special cases:
// As discussed above, when x < 0, x is not a palindrome.
// Also if the last digit of the number is 0, in order to be a palindrome,
// the first digit of the number also needs to be 0.
// Only 0 satisfy this property.
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10;
}
}