Minimum One Bit Operations to Make Integers Zero

hard bit manipulation gray code math

Problem

Transform an integer n into 0 using two operations, any number of times: (1) flip the rightmost (0th) bit; (2) flip the i-th bit only if bit (i−1) is 1 and bits (i−2)…0 are all 0. Return the minimum number of operations needed to reach 0.

Inputn = 3
Output2
"11" → "01" (op 2, since bit 0 is 1) → "00" (op 1). Two operations.
Inputn = 6
Output4
"110" walks through "010" → "011" → "001" → "000" in 4 moves.

def minimumOneBitOperations(n):
    ans = 0
    while n:
        ans ^= n
        n >>= 1
    return ans
function minimumOneBitOperations(n) {
  let ans = 0;
  while (n) {
    ans ^= n;
    n >>= 1;
  }
  return ans;
}
int minimumOneBitOperations(int n) {
    int ans = 0;
    while (n != 0) {
        ans ^= n;
        n >>>= 1;
    }
    return ans;
}
int minimumOneBitOperations(int n) {
    int ans = 0;
    while (n != 0) {
        ans ^= n;
        n >>= 1;
    }
    return ans;
}
Time: O(log n) Space: O(1)