LeetCode-Easy-009-Palindrome Number

本文探讨了如何判断一个整数是否为回文数,提供了两种算法实现,包括整数翻转法和半遍历法,并详细解析了算法中的边界条件处理,如负数、零和特殊位数情况。

描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

难度

Easy

题目链接:

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

思路

首先,负数肯定不满足。对于正整数,借鉴题目 007 中的翻转整数的例子,满足条件的整数翻转之后仍然是它本身。于是我们可以得到下面的答案:

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) return false;
        return x == reverse(x);
    }
    
    public int reverse(int x) {
        long ret = 0;
        for (; x!=0; x/=10) {
            ret = ret * 10 + x % 10;
        }
        return ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE ? 0 : (int) ret;
    }
}

考虑到满足条件的整数本身是对称的,即 12321 这样的才能满足要求,也就是说,我们上面的遍历实际没有必要对整数的所有位数进行遍历,只要遍历到一半就够了。

    public static void main(String ...args) {
        System.out.println(0 + " : " + isPalindrome(0));
        System.out.println(10010 + " : " + isPalindrome(10010));
        System.out.println(1001 + " : " + isPalindrome(1001));
        System.out.println(121 + " : " + isPalindrome(121));
        System.out.println(-121 + " : " + isPalindrome(-121));
        System.out.println(123 + " : " + isPalindrome(123));
    }
    
    // 错误代码
    public static boolean isPalindrome(int x) {
        if (x < 0) return false;
        int half = 0;
        while (x > half) {
            half = half * 10 + x % 10;
            x /= 10;
        }
        return half == x;
    }

这里我们使用 half 表示数字的一半。然而,我们运行程序发现 121 返回了 false. 这是因为,此时 x=1, half=12. 因为 121 是三位数,所以,我们需要在最后的 return 中加入一个条件 half | 10 == x. (就是整数位数的奇偶问题,奇数位数需要除以10)

但此时又存在另一个问题,考虑 10010,当循环结束时,x = 10, half = 10. 将返回 true, 而它应该返回 false. 因为它是奇数位数,我们本应该除以 10 再比较的!

所以,我们需要对 10 的倍数这种特例进行处理,于是最终算法,

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

在第一个 if 语句中不要忘记对 0 进行处理!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值