Skip to content

Differing Bit Count

Easy#xor#bit-counting~15 min

The mission

Problem

Write two non-negative whole numbers in binary, one above the other and aligned on the right. Count the positions where their binary digits disagree. Missing digits on the left of the shorter number count as zeros.

Examples

Input:  a = 1, b = 4
Output: 2
Why:    001 against 100 disagrees in the first and last positions
Input:  a = 7, b = 10
Output: 3
Why:    0111 against 1010 disagrees everywhere except the second position from the right
Input:  a = 5, b = 5
Output: 0
Why:    edge case, a number never disagrees with itself

Hints

0 / 3

Target time
O(log max(a, b))
Target space
O(1)

Constraints

  • a and b are non-negative integers

Stuck on the idea rather than the code? Counting Set Bits covers it.

Python 3Ctrl+Enter runs
Custom test case