一个整数(按照规则)经过几次替换变为1 Integer Replacement

问题:

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

解决:

① 递归解决。

class Solution {//7ms
    public int integerReplacement(int n) {
        long num = n;//避免栈溢出
        return helper(num);
    }
    public int helper(long n){
        if(n == 1) return 0;
        if(n == 3) return 2;
        if(n % 2 == 0){
            return helper(n / 2) + 1;
        }else{
            return Math.min(helper(n + 1),helper(n - 1)) + 1;
        }
    }
}

② 

利用bit位的操作。如果这个数偶数,那么末位的bit位一定是0。如果一个数是奇数,那么末位的bit位一定是1。对于偶数,操作是直接除以2。

对于奇数的操作:
如果倒数第二位是0,那么n-1的操作比n+1的操作能消掉更多的1。
1001 + 1 = 1010
1001 - 1 = 1000
如果倒数第二位是1,那么n+1的操作能比n-1的操作消掉更多的1。
1011 + 1 = 1100
1111 + 1 = 10000

还有一个tricky的地方是,为了防止integer越界,可以将n先转换成long。long N = n;这样的处理。

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

③ 在discuss中看到的。

class Solution {//4ms
    public int integerReplacement(int n) {
        int count = 0;
        if(n <= 1) return count;
        while(n != 1){
            if(n % 2 == 0){
                n >>>= 1;
            }else{
                if(n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)){
                    n -= 1;
                }else{
                    n += 1;
                }
            }
            count ++;
        }
        return count;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1601098

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值