Drill

ProblemsPython › patterns

How many switches differ

easypatternsBit manipulationMathPython

Two configuration fields are compared to see how far apart they are: the count of bit positions where the two disagree.

differing_bits(before: int, after: int) → int

Solve it in the editor →

Where you start

def differing_bits(before: int, after: int) -> int:
    

Worked examples

CallResult
differing_bits(1, 4)2
differing_bits(3, 1)1
differing_bits(0, 0)0
differing_bits(7, 7)0

Hint

Exclusive-or sets exactly the bits where the two disagree. Then it is only a matter of counting the set bits in that.

Reference solution in Python
def differing_bits(before: int, after: int) -> int:
    differing = before ^ after
    count = 0
    while differing > 0:
        count += differing & 1
        differing >>= 1
    return count

The same problem in another language

More patterns problems in Python