leetcode----回文数

题目:

判断一个整数是否是回文数?回文数是指正序和倒序为一样的

示例;

121       121  true

-121      121-   false

10       01   false

思路:

第一步:判断是否小于0,若小于0直接判断为false

第二步:若大于0,将其进行整数的反转后比较与反转前是否相等即可判断其是否为回文数。

public class Id09Palindrome {


    public static void main(String[] args) {
        Id09Palindrome palindrome = new Id09Palindrome();
        System.out.println(palindrome.isPalindrome(2147483647));
    }

    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int size = String.valueOf(x).length();
        int factor;
        if (size == 1) {
            return true;
        } else {
            factor = (int) Math.pow(10, size - 1) + 1;
        }
        //98 908 302 1000
        if ((x + 1) % factor == 0) return false;
        int result = x % factor;
        int resultSizeLimit = getResultLimit(size);
        if (result != 0) {
            if (result % 10 != 0
                    || result < resultSizeLimit) {
                return false;
            } else {
                x = division(result);
            }
        } else {
            return true;
        }
        return isPalindrome(x);
    }

    /**
     * 余数限制 100030001  余数30000>10000  限制 1000021
     *
     * @return
     */
    private int getResultLimit(int size) {
        if (size % 2 == 0) {
            return (int) Math.pow(10, size / 2);
        } else {
            return (int) Math.pow(10, (size - 1) / 2);
        }
    }

    /**
     * make 330000->33
     *
     * @param x
     * @return
     */
    private int division(int x) {
        for (int i = String.valueOf(x).length(); i > 0; i--) {
            int tmp = (int) Math.pow(10, i - 1);
            if (x % tmp == 0) {
                return x / tmp;
            }
        }
        return 0;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值