397. Integer Replacement

来源:互联网 发布:2级钢筋弯勾 算法 编辑:程序博客网 时间:2024/06/17 03:58

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:8Output:3Explanation:8 -> 4 -> 2 -> 1

Example 2:

Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1

思路:以bit manipulation的方式来思考本题,

偶数没的说,奇数是加1还是减1需要考虑,看那个操作自后的bitCount更小(3是个特例)

因为偶数除以2可以更快的靠近1

奇数也是通过先转换成偶数除以2来得到消除某一位的效果


class Solution {public:    int integerReplacement(int n) {        if(n == 2147483647) return 32;        int cnt = 0;        while(n != 1) {            if((n & 1) == 0) {                n = (n >> 1);            } else if(n == 3 || __builtin_popcount(n+1) > __builtin_popcount(n-1)) {                n--;            } else {                n ++;            }            cnt++;        }        return cnt;    }};



0 0
原创粉丝点击