Recursive easy to understand method


  • 0
    Z

    My method might be little bit slow than the one with bitCount, but more straightforward and easy to understand.

        public int integerReplacement(int n) {
            return helper(n);
        }
        int helper(long n){
            //base 
            if(n==1)return 0;
            if(n==2)return 1;
            //even  always good to remove the LSB if you can
            if(n%2==0)return 1+helper(n/2);
            //odd
            return 1+Math.min(helper(n+1), helper(n-1));
        }
    

Log in to reply
 

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