问题来源:https://leetcode.com/problems/palindrome-number/
/**
*
* <p>
* ClassName PalindromeNumber
* </p>
* <p>
* Description Determine whether an integer is a palindrome(n. 回文). 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.
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月24日 上午10:48:32
* </p>
* @version V1.0.0
*
*/
public class PalindromeNumber {
public boolean isPalindrome(int x) {
// 该判断在此题无作用,主要用来解决判断负数回文的情况
// 因为正数比负数少表示一位,所以当为Integer.MIN_VALUE的时候,是无法取绝对值转为正数的
if (x == Integer.MIN_VALUE) {
return false;
}
if (x < 0) {
// 这题说的不清晰,并没有明确说明负数是否可以是回文的,我认为如果不考虑符号的话,负数也可以是回文的,但是该题所提供的测试用例全部认为负数都是非回文的
return false;
}
// 我的解题思路是从低位开始,不断的逆向构造一个整数,那么该整数如果与要判断的数一样的话,那么肯定就是回文的
int temp = x;
int reverse_x = 0;
while (temp > 0) {
reverse_x = reverse_x * 10 + temp % 10;
temp /= 10;
}
return reverse_x == x;
}
public static void main(String[] args) {
// boolean palindrome = new PalindromeNumber().isPalindrome(2050880502);
boolean palindrome = new PalindromeNumber().isPalindrome(-205088050);
System.out.println(palindrome);
}
}
原文:http://blog.csdn.net/shijiebei2009/article/details/44596549