397. 整数替换

一开始想用dp[],但是爆内存了
后面改成递归,AC了

class Solution:
    def __init__(self):
        self.d = dict()
        self.d[1] = 0
        self.d[2] = 1


    def integerReplacement(self, n: int) -> int:
        if n in self.d:
            return self.d[n]
        else:
            if n % 2 == 0:
                return self.integerReplacement(n//2) + 1
            else:
                L,R = self.integerReplacement(n-1), self.integerReplacement(n+1)
                return min(L,R) + 1

按照题意描述就能写出上面的代码

还有一种位运算的技巧

class Solution {
    public int integerReplacement(int _n) {
        long n = _n;
        int ans = 0;
        while (n != 1) {
            if (n % 2 == 0) {
                n >>= 1;
            } else {
                if (n != 3 && ((n >> 1) & 1) == 1) n++;
                else n--;
            }
            ans++;
        }
        return ans;
    }
}

来源:https://leetcode-cn.com/problems/integer-replacement/solution/gong-shui-san-xie-yi-ti-san-jie-dfsbfs-t-373h/

主要是考虑到n为奇数的情况,此时n的最后一位必为1
考虑两种情况:

  1. n的次低位(倒数第二位)为1,则考虑+1,因为该操作能够消去一段连续的1
  2. n的次低位为0,考虑-1,因为+1位数里面的1的个数不会变化,但是-1能够消去一个1
    再考虑一个特殊情况:3,此时应该-1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值