Recursive solution in java, very very easy!!!


  • 0
    F
        public int integerReplacement(int n) {
            return helper(n);
        }
    
        private int helper(long n) {
            if (n == 1) {
                return 0;
            }
            if (n % 2 == 0) {
                return helper(n / 2) + 1;
            } else {
                return Math.min(helper(n - 1), helper(n + 1)) + 1;
            }
        }
    

    To avoid overflow, I use a helper which takes long as parameters.


Log in to reply
 

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