classic recursion


  • 0
    M

    public class Solution {
    int result = Integer.MAX_VALUE;
    public int integerReplacement(int n) {
    if (n == 1) {
    return 0;
    }
    helper(n, 0);
    return result;
    }
    public void helper (int n, int index) {
    if (n < 0) {
    return;
    }
    if (n == 1) {
    result = Math.min(result, index);
    return;
    }
    if (n % 2 == 0) {
    helper(n / 2, index + 1);
    } else {
    helper(n / 2 + 1, index + 2);
    helper(n / 2, index + 2);
    }
    }
    }


Log in to reply
 

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