397. Integer Replacement

本文探讨了LeetCode上的经典算法问题——整数替换。通过分析给定正整数n的操作规则,介绍了如何通过最少步骤将n转换为1的最优策略,并提供了一段修正后的Java代码实现。

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

原题

Given a positive integer n and you can do operations as follow:

If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?

Example 1:

Input:
8

Output:
3

Explanation: 8 -> 4 -> 2 -> 1

Example 2:

Input:
7

Output:
4

Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1

代码实现

Following coding refers to
A couple of Java solutions with explanations
But it has a bug of overflowing and I fix it.

    public int IntegerReplacement(int n) {
        int cnt = 0;
        long bign = (long)n; //n = Int32.MaxValue(2147483647),adds 1 and would overflow
        while (bign != 1) {
        if ((bign & 1) == 0) { //even number
            bign >>= 1;
          } 
          //It is enough to examine the last two digits to figure out 
          //whether incrementing or decrementing will give more 1's. Indeed, 
          //if a number ends with 01, 
          //then certainly decrementing is the way to go. Otherwise, if it ends with 11, 
          //then certainly incrementing is at least as good as decrementing (*011 -> *010 / *100) or
          // even better (if there are three or more 1's).
          else if (bign == 3|| ((bign >> 1) & 1) == 0) { //*01
            --bign;
          }
          else { //*11
            ++bign;
        }
        ++cnt;
       } 
       return cnt;
    }

题库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值