Problems › JavaScript › patterns
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
Where you start
function differingBits(before, 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 JavaScript
function differingBits(before, after) {
let differing = before ^ after;
let count = 0;
while (differing > 0) {
count += differing & 1;
differing >>= 1;
}
return count;
}