Number of Bit Changes to Make Two Integers Equal

You are given two positive integers n and k.

You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.

Return the number of changes needed to make n equal to k. If it is impossible, return -1.

Example 1
Inputn = 13, k = 4
Output2
Changing the first and fourth bits of n = (1101)2 makes it equal to k = (0100)2, requiring 2 changes.
Example 2
Inputn = 21, k = 21
Output0
n and k are already equal, so no changes are needed.

Constraints

  • 1 <= n, k <= 10^6

Asked at 1 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate