9. Palindrome Number 回文 my second leetcode 20170807

时间:2022-05-30 04:22:33

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

判断一个整形数字是否为回文串

 public class Solution {
public boolean isPalindrome(int x) {
int res =0;
int temp = 0;
int begin = x;
if(x<0) return false;
while(x!=0){
temp = temp * 10 + x % 10;
if(temp>Integer.MAX_VALUE) return false;
res = temp;
x /=10;
}
if(begin == res )
return true;
else
return false;
}
}

9. Palindrome Number 回文 my second leetcode 20170807

总结:这个题和reverse ingeter 非常类似,区别在于他没有负数,同时如果你的反过来超过了最大值那么肯定不是回文数,如果没超过的话再去对比和原数是否相等,相等的话才是回文