How many switches differ
Two configuration fields are compared to see how far apart they are: the count of bit positions where the two disagree.
- Compare the two fields bit by bit.
- Return how many positions hold different bits.
- Two identical fields differ in nothing.
- Both values are zero or more.
differingBits(before: int, after: int) → int
Java 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.
Where you start
int differingBits(int before, int after) {
}
Worked examples
| Call | Result |
|---|---|
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 Java
int differingBits(int before, int after) {
int differing = before ^ after, count = 0;
while (differing > 0) {
count += differing & 1;
differing >>= 1;
}
return count;
}