LeetCode

题目

URL:https://leetcode.com/problems/palindrome-number

解法

想办法取出回文数左右两边的数。

首先取右面的数,可以通过“取余”方法取出(LeetCode - 7 - Reverse Integer)。仔细想一下,右面的数取出来了,左面的数自然就呈现出来了,就是“未取余”的部分。

当回文数长度为奇数时,只需要判断长的一方除以 10 是否相等;当回文数长度为偶数时,两方一样长,判断两方是否相等。

    public boolean isPalindrome(int x) {
        if (x < 0 || x != 0 && x % 10 == 0) return false;
        int left = 0;
        while (x > left) {
            left = left * 10 + x % 10;
            x = x / 10;
        }
        return x == left || left / 10 == x;
    }

取余法,时间复杂度O(x.length),运行时间约为 200 ms

总结

多多尝试,思路要放得开。

原文地址:https://www.cnblogs.com/Piers/p/7153168.html