Toggle Bits — Number of Bits to Flip

E · easyP · Verified PYQbit-manipulation

Given two integers A and B, find the number of bits that need to be flipped to convert A to B. (i.e., count the number of set bits in A XOR B)

Input
10 20
Output
4
XOR both numbers. Count set bits in XOR result using bin(a^b).count("1").
10 = 01010, 20 = 10100. XOR = 11110 → 4 set bits → 4 flips needed.
← Toggle All Bits After MSB (Including MSB)Train Travel Time on Bridge →
Report an issue with this question