首页 > 其他 > 详细

Palindrome Number

时间:2015-03-24 21:23:27      阅读:299      评论:0      收藏:0      [点我收藏+]

问题来源: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);
    }

}

Palindrome Number

原文:http://blog.csdn.net/shijiebei2009/article/details/44596549

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!