Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Bit Manipulation

Minimum One-Bit Operations to Reach Zero

Hard · Bit Manipulation · Asked at Google, Amazon

You may change a number with two operations:

  1. Flip the rightmost bit (bit 0).
  2. Flip bit i if bit i − 1 is 1 and bits i − 2 … 0 are all 0.

For each query x, print the minimum number of operations to turn x into 0.

Input

First line: q. Next q lines: one integer x each.

Output

q lines — the minimum number of operations.

Constraints

The operations walk the Gray-code sequence, and x sits at position g⁻¹(x) in it, so the answer is the inverse Gray code: ans = x ^ (x >> 1) ^ (x >> 2) ^ … — equivalently, for every set bit k from high to low, ans = 2^(k+1) − 1 − ans.

Example 1

Input

3
3
6
0

Output

2
4
0

Hints

  1. Try small numbers by hand: 0, 1, 3, 2, 6, 7, 5, 4 … is the order in which numbers are reached from 0.
  2. That sequence is the Gray code: the i-th number is i ^ (i >> 1).
  3. So the answer for x is the position i of x in the Gray code — the inverse Gray code.

Approach

The two operations are exactly the moves between neighbouring Gray codes, and every number is visited once along the sequence, so the minimum number of steps from x to 0 is the index of x in it. The inverse Gray code is the XOR of all right shifts: ans = x ^ (x >> 1) ^ (x >> 2) ^ … — computed by repeatedly XOR-ing ans with x and shifting x right until it is 0.

Complexity: O(log x) per query

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int q;
    cin >> q;
    while (q--) {
        long long x, ans = 0;
        cin >> x;
        while (x) {
            ans ^= x;
            x >>= 1;
        }
        cout << ans << "\n";
    }
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
out = []
for x in data[1 : 1 + data[0]]:
    ans = 0
    while x:
        ans ^= x
        x >>= 1
    out.append(ans)
print("\n".join(map(str, out)))

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int q = (int) in.nval;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < q; i++) {
            in.nextToken();
            long x = (long) in.nval, ans = 0;
            while (x != 0) {
                ans ^= x;
                x >>= 1;
            }
            sb.append(ans).append('\n');
        }
        System.out.print(sb);
    }
}

Solve Minimum One-Bit Operations to Reach Zero online · All practice problems