leetcode:397. Integer Replacement 详细分析及源代码


     位操作这一块不熟,所以特意去leetcode上找题看了一下。

     题目如下:

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

  1. If n is even, replace n with n/2.
  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

首先,我们考虑一下如果要把一个偶数变成1需要多少步,这么说,除了一开始的那个1,那么剩下的0贡献1步,1贡献2步,所以我们要做的就是尽可能消除1的个数

n为偶数就不用说了吧 直接除2

n为奇数这个时候我们需要分情况讨论

倒数第二位位1,那么我们选择+1,至少可以消除1个1,然而-1只能消除1个1,这时候我们选择+1

 倒数第二位为0,选择+1,不能消除1,选择减1可以消除最后一个1,这时候我们选择减1

不过要记得处理一下特殊情况3

源代码如下:

public class Solution {
    public int integerReplacement(int n) {
        long N = n;
        int count = 0;
        while(N != 1) {
            if(N % 2 == 0) {
                N = N >> 1;
            }
            else {
                if(N == 3) {
                    count += 2;
                    break;
                }
                N = (N & 2) == 2 ? N + 1 : N - 1;
            }
            count ++;
        }
        return count;

    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值