- First we need to convert each number to its binary representation. We can do that using
bin(x)[2:]
- Next, we need to append leading 0s as needed. We need to append
abs(len(start) - len(goal))
leading 0s to whichever (ofstart
orgoal
) has a shorter binary representation - 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
- Nothing too complex here; let's implement it!
classSolution: defminBitFlips(self, start: int, goal: int) ->int: start=bin(start)[2:] goal=bin(goal)[2:] leading_zeros=''.join('0'*abs(len(start) -len(goal))) iflen(start) <len(goal): start=leading_zeros+startelse: goal=leading_zeros+goalflips=0fori, jinzip(start, goal): ifi!=j: flips+=1returnflips
- Given test cases pass
- Submitting...
Solved! Easy peasy lemon squeezy! 🍋