#3226

Number of Bit Changes to Make Two Integers Equal

Easy
Bit ManipulationBit ManipulationXORCounting Bits
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal approach uses bit manipulation to directly calculate the number of changes needed without iterating through each bit. By using the XOR operation, we can quickly identify which bits differ between n and k.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the XOR of n and k to find differing bits.
  2. 2Step 2: Count the number of 1s in the result of the XOR operation.
  3. 3Step 3: Check if the bits in k that are 1 can be matched by bits in n that are 1.
  4. 4Step 4: If any bit in k is 1 and the corresponding bit in n is 0, return -1.
  5. 5Step 5: Return the count of differing bits.
solution.py11 lines
1# Full working Python code
2
3def count_bit_changes(n, k):
4    if n == k:
5        return 0
6    xor = n ^ k
7    changes = bin(xor).count('1')
8    if (n & k) != k:
9        return -1
10    return changes
11

Complexity note: The complexity is O(log n) because we are only processing the bits of the integers, which is proportional to the number of bits in the integers.

  • 1Using XOR helps identify differing bits efficiently.
  • 2Counting bits can be done using built-in functions, simplifying the process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.