Drill

ProblemsC# › patterns

How many switches differ

easypatternsBit manipulationMathC#

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

C# 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

public int DifferingBits(int before, int after) {
    
}

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 C#
public int DifferingBits(int before, int after) {
    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 C#