Drill

ProblemsGo › patterns

How many switches differ

easypatternsBit manipulationMathGo

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

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

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func differingBits(before int, after int) int {
	
}

Worked examples

CallResult
differingBits(1, 4)2
differingBits(3, 1)1
differingBits(0, 0)0
differingBits(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 Go
func differingBits(before int, after int) int {
	differing, count := before^after, 0
	for differing > 0 {
	    count += differing & 1
	    differing >>= 1
	}
	return count
}

The same problem in another language

More patterns problems in Go