Drill

ProblemsJavaScript › patterns

How many switches differ

easypatternsBit manipulationMathJavaScript

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

Solve it in the editor →

Where you start

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

The same problem in another language

More patterns problems in JavaScript