Java recursive solution and easy to understand.


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

Log in to reply
 

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