Last Updated: 22 Feb, 2026

Gray Code Transformation

Hard

Problem statement

You are given an integer n. Your goal is to transform n into 0 using a specific set of bitwise operations. You want to find the minimum number of operations required.


The allowed operations on the binary representation of n are:

Operation 1: You can always change the rightmost (0th) bit.
Operation 2: For any bit at position i > 0, you can change it if and only if the bit at position i-1 is 1, and all bits from i-2 down to 0 are 0.

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


Insight (Gray Code):

This problem describes the transformation from a standard binary number to its corresponding Gray code representation, and then finding the integer value of that Gray code. The number of steps to transform a number n to 0 under these rules is equivalent to the integer value of the Gray code of n. The Gray code of n can be calculated efficiently using the bitwise formula: n XOR (n >> 1).


Input Format:
The first line contains a single integer T, the number of test cases.
Each of the next T lines contains a single integer n.


Output Format:
For each test case, your function should return a single integer representing the minimum number of operations.