LeetCode 788. 旋转数字

本文提供了一种解决LeetCode旋转数字问题的有效方法。通过使用一个映射来转换可旋转的数字,文章详细介绍了如何判断一个数在旋转180度后是否变成不同的有效数。代码实现简洁明了,避免了不必要的复杂性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

题目地址:https://leetcode-cn.com/problems/rotated-digits/
思路:模拟一下即可

代码

我看了一下官方的题解,我这里是用了一个map,其实搞复杂了,我把优化的点写到代码上把

public class Solution {

    public int rotatedDigits(int N) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 0);
        map.put(1, 1);
        map.put(8, 8);
        map.put(2, 5);
        map.put(5, 2);
        map.put(6, 9);
        map.put(9, 6);
        int total = 0;
        for (int i = 1; i <= N; i++) {
            int M = i;
            boolean flag = true;
            int tempNum = 0;
            int mul = 1;
            while (M != 0) {
                int num = M % 10;
                // 可以改成 num == 3 || num == 4 || num == 7 
                // falg = false
                Integer mapNum = map.get(num);
                if (mapNum == null) {
                    flag = false;
                    break;
                }
                tempNum = tempNum + mapNum * mul;
                mul *= 10;
                M /= 10;
            }
            if (flag && tempNum != i) {
                total++;
            }
        }
        return total;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值