397. 整数替换

给定一个正整数 n,你可以做如下操作:

1. 如果 n 是偶数,则用 n / 2替换 n。
2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。
n 变为 1 所需的最小替换次数是多少?

示例 1:

输入:
8

输出:
3

解释:
8 -> 4 -> 2 -> 1
示例 2:

输入:
7

输出:
4

解释:
7 -> 8 -> 4 -> 2 -> 17 -> 6 -> 3 -> 2 -> 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-replacement
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
    public int integerReplacement(int n) {
      return (int)func((long)n);
    }
    public long func(long n){
        if(n ==1) return 0;
      if(n%2==0){
          return  1 + func(n/2);
      }else  { 
          return 1 + Math.min(func(n+1),func(n-1));
      }
    }
}
100%class Solution {
    public int integerReplacement(int n) {
        if(n < 2)
            return 0;
        
        int res = 0;
        n = n == Integer.MAX_VALUE ? n - 1 : n; //这是个坑点。如果再加 1 就要超过int的范围了,也可以直接返回32
        
        for(;n != 1; res++)
            n = 0 == (n & 1) ? n >> 1   // 偶数, 直接右移
                : 3 == (n & 3) && n != 3 ? n + 1 : n - 1;   //若 n 的最后两位是11,加1,之后可以连续做两次除法,降低了次数

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值