Bit Manipulation
Common Operations
x.bit_count(): Returns the number of 1s in the binary representation of x. Can also be interpreted as the minimum number of powers of 2 needed to represent x.
Brain Teasers
2749. Minimum Operations to Make the Integer Zero
Let x = num1 - k * num2, then the problem transforms to: Can x be represented using k powers of 2 (duplicates allowed)?
Find the upper and lower bounds of x and enumerate. Plot x = num1 - k * num2 with k as x-axis and x as y-axis. The answer lies in some points on this line in the first quadrant. Analyze the equation x=2^(i1)+…2^(ik) to find possible x values.
Since the smallest power of 2 is 1, x >= k When x is maximum, k is minimum, i.e. k = x.bit_count()
Enumerate k from small to large, the first satisfying equation is the answer.
3495. Minimum Operations to Make All Array Elements Zero
Dividing a number by 4 and flooring it: binary right shift by two bits For a number with n bits in binary representation, it requires (n+1)//2 operations to become 0
| |