Problem solution · Java

Minimum One Bit Operations to Make Integers Zero

Minimum One Bit Operations to Make Integers Zero: a Java solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
34 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Minimum One Bit Operations to Make Integers Zero, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 34 lines of Java from the credited upstream file 1611.java.
  • The implementation keeps its working state in language-native values and containers.
  • 1 loop block detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum One Bit Operations to Make Integers Zero · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minimumOneBitOperations(int n) {    // Observation: e.g. n = 2^2    //        100 (2^2 needs 2^3 - 1 ops)    // op1 -> 101    // op2 -> 111    // op1 -> 110    // op2 -> 010 (2^1 needs 2^2 - 1 ops)    // op1 -> 011    // op2 -> 001 (2^0 needs 2^1 - 1 ops)    // op1 -> 000    //    // So 2^k needs 2^(k + 1) - 1 ops. Note this is reversible, i.e., 0 -> 2^k    // also takes 2^(k + 1) - 1 ops.     // e.g. n = 1XXX, our first goal is to change 1XXX -> 1100.    //   - If the second bit is 1, you only need to consider the cost of turning    //     the last 2 bits to 0.    //   - If the second bit is 0, you need to add up the cost of flipping the    //     second bit from 0 to 1.    // XOR determines the cost minimumOneBitOperations(1XXX^1100) accordingly.    // Then, 1100 -> 0100 needs 1 op. Finally, 0100 -> 0 needs 2^3 - 1 ops.    if (n == 0)      return 0;    // x is the largest 2^k <= n.    // x | x >> 1 -> x >> 1 needs 1 op.    //     x >> 1 -> 0      needs x = 2^k - 1 ops.    int x = 1;    while (x * 2 <= n)      x <<= 1;    return minimumOneBitOperations(n ^ (x | x >> 1)) + 1 + x - 1;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗