Count bits to flip to convert A to B

Easy

Problem

Return how many bits must be flipped to turn integer a into integer b — the number of positions where their bits differ.

Example 1

Input:  a = 10 (1010), b = 20 (10100)
Output: 4

Also asked as: Count number of bits to be flipped to convert A to B

Test cases

Case 1

Input:    10, 20
Expected: 4

Case 2

Input:    0, 15
Expected: 4

Case 3

Input:    1, 2
Expected: 2

Case 4

Input:    7, 7
Expected: 0

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Popcount of A XOR B

Time O(bits)Space O(1)

A ^ B has a 1 exactly where the bits differ.

function bitsToFlip(a, b) {
let x = a ^ b, count = 0;
while (x) { x &= x - 1; count++; }
return count;
}