Skip to content

Commit 376b050

Browse files
My solution to 2220
1 parent 16bc910 commit 376b050

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

problems/2220/jeremymanning.md

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,37 @@
11
# [Problem 2220: Minimum Bit Flips to Convert Number](https://leetcode.com/problems/minimum-bit-flips-to-convert-number/description/?envType=daily-question)
22

33
## Initial thoughts (stream-of-consciousness)
4+
- First we need to convert each number to its binary representation. We can do that using `bin(x)[2:]`
5+
- Next, we need to append leading 0s as needed. We need to append `abs(len(start) - len(goal))` leading 0s to whichever (of `start` or `goal`) has a shorter binary representation
6+
- Finally, now that the two representations have the same length, we can just loop through bit by bit and count up the number of mismatches
47

58
## Refining the problem, round 2 thoughts
9+
- Nothing too complex here; let's implement it!
610

711
## Attempted solution(s)
812
```python
9-
class Solution: # paste your code here!
10-
...
13+
class Solution:
14+
def minBitFlips(self, start: int, goal: int) -> int:
15+
start = bin(start)[2:]
16+
goal = bin(goal)[2:]
17+
18+
leading_zeros = ''.join('0' * abs(len(start) - len(goal)))
19+
if len(start) < len(goal):
20+
start = leading_zeros + start
21+
else:
22+
goal = leading_zeros + goal
23+
24+
flips = 0
25+
for i, j in zip(start, goal):
26+
if i != j:
27+
flips += 1
28+
return flips
1129
```
30+
- Given test cases pass
31+
- Submitting...
32+
33+
![Screenshot 2024-09-10 at 11 18 01 PM](https://github.com/user-attachments/assets/1b2f904a-897c-4df4-8563-33cc785bb26b)
34+
35+
Solved! Easy peasy lemon squeezy! 🍋
36+
37+

0 commit comments

Comments
 (0)