LeetCode-in-Java

1611. Minimum One Bit Operations to Make Integers Zero

Hard

Given an integer n, you must transform it into 0 using the following operations any number of times:

Return the minimum number of operations to transform n into 0.

Example 1:

Input: n = 3

Output: 2

Explanation: The binary representation of 3 is “11”.

“11” -> “01” with the 2nd operation since the 0th bit is 1.

“01” -> “00” with the 1st operation.

Example 2:

Input: n = 6

Output: 4

Explanation: The binary representation of 6 is “110”.

“110” -> “010” with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.

“010” -> “011” with the 1st operation.

“011” -> “001” with the 2nd operation since the 0th bit is 1.

“001” -> “000” with the 1st operation.

Constraints:

Solution

import java.util.LinkedList;

public class Solution {
    public int minimumOneBitOperations(int n) {
        return calc(calculateOneIndex(n));
    }

    private int calc(LinkedList<Integer> indices) {
        if (indices.isEmpty()) {
            return 0;
        }
        int index = indices.removeLast();
        return stepOfExp(index) - calc(indices);
    }

    private LinkedList<Integer> calculateOneIndex(int n) {
        LinkedList<Integer> result = new LinkedList<>();
        int index = 1;
        while (n > 0) {
            if (n % 2 == 1) {
                result.add(index);
            }
            n >>= 1;

            index++;
        }
        return result;
    }

    private int stepOfExp(int index) {
        int result = 1;
        while (index > 0) {
            result <<= 1;
            index--;
        }
        return result - 1;
    }
}