题目如下:
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.
非常简单的问题,整数先转化为字符串,两边对称的位置依次比较,全部相同则为回文,否则不是。可以从头尾开始,也可以从中间开始。
代码如下(通过OJ):
public class Solution {
public boolean isPalindrome(int x) {
boolean result = true;
if(x < 0)
return false;
char[] str = Integer.toString(x).toCharArray();
for(int i=0;i<str.length / 2;i++){
if(str[i] != str[str.length-1-i]){
result = false;
break;
}
}
return result;
}
}