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.
Subscribe to see which companies asked this question
package leetcode;
/**
* 回文
* @author Mouse
*
*/
public class Solution {
public static boolean isPalindrome(int x) {
if (x<0) return false;
if (x<10) return true;//只有一个元素
String s=String.valueOf(x);
int len=s.length();
int i=0;//开始位置
int j=len-1;//结束的位置
while (i<j) {
if (s.charAt(i)==s.charAt(j)) {
i++;
j--;
}else{
return false;
}
}
return true;
}
public static void main(String[] args) {
boolean a=isPalindrome(1221);
System.out.println(a);
}
}
本文介绍了一种不使用额外空间判断整数是否为回文的方法。通过将整数转换为字符串并比较首尾字符的方式实现,同时考虑了负数不能成为回文的情况。
373

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



