C++ 3-Line Recursion Solution...3ms

  • 0

    The idea is really easy, find the shortest path to '1' by using the function min(a,b)

    Since n+1 is involved, overflow has to be considered.

    Please let me know your doubts and suggestions, thanks!

        int integerReplacement(int n) {
            if (n == INT_MAX) return 32;
            if (n == 1) return 0;
            return n%2 == 0 ? 1 + integerReplacement(n/2) : min(1+integerReplacement(n+1),1+integerReplacement(n-1));

Log in to reply

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