clueless coding // TODO: be smarter

LeetCode Integer Replacement: CPP Solution



TL;DR Code Solution


int integerReplacement(int n) {

    if (n == 1) {
        return 0;
    }

    if (n == 2147483647) {
        return integerReplacement(n-1);
    }

    if (n % 2 == 0)
        return 1 + integerReplacement(n/2);

    else
        return 1 + min(integerReplacement(n-1), integerReplacement(n+1));

}