2 Lines Recursive C++, Elegant Code Handled ALL Case


  • 0

    long long int is the key, otherwise might get error on 2147483647.

    class Solution {
    public:
        int integerReplacement(long long int n) {
            if (n == 1) return 0;
            return ((n % 2) ? min(integerReplacement(n + 1), integerReplacement(n-1)) : integerReplacement(n / 2)) + 1;
        }
    };
    

Log in to reply
 

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