#2220
Minimum Bit Flips to Convert Number
EasyBit ManipulationBit ManipulationXOR
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using the XOR operation allows us to quickly identify which bits differ between the two numbers. Each differing bit corresponds to a needed flip, making this approach efficient.
⚙️
Algorithm
2 steps- 1Step 1: Calculate the XOR of start and goal to identify differing bits.
- 2Step 2: Count the number of 1s in the result of the XOR operation, which indicates how many bits need to be flipped.
solution.py4 lines
1# Full working Python code
2
3def minBitFlips(start, goal):
4 return bin(start ^ goal).count('1')ℹ
Complexity note: The time complexity is O(n) due to the need to count the bits in the result of the XOR operation, which is efficient compared to the brute-force method.
- 1Using XOR simplifies the problem of finding differing bits.
- 2Counting bits can be done efficiently with built-in functions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.