a solution with bit manipulation


  • 0
    A

    for each bit if it is 0 we need 1 step. if it is 1 no matter we plus or minus 1, it will take 2 steps.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.