Created
April 7, 2022 22:05
-
-
Save aaronshaver/612ad218ce04254b3f5a14eeae387366 to your computer and use it in GitHub Desktop.
Bit mask and bit shifting example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://leetcode.com/problems/minimum-bit-flips-to-convert-number/ | |
# this works by making a bit mask using left shift 1 << i, e.g. 1 << 3 == a mask of 1000 | |
# then bitwise AND with the num, gives us a binary num that indicates whether both mask | |
# and num have a 1 in that digit; e.g. 10 & (1<<2) == 000, and 7 & (1<<2) == 100 | |
# then bit shift right chops off the trailing 0s | |
# so in this case we'd have 0 for the start decimal num of 10, and 1 for the goal num of 7, | |
# meaning digit at that place has to change for the start num, and thus our count of | |
# operations has to increase | |
class Solution: | |
def minBitFlips(self, start: int, goal: int) -> int: | |
length = max(len(bin(start)[2:]), len(bin(goal)[2:])) # '2:'' chops off 0b | |
count = 0 | |
for i in range(length): | |
if ((start & (1 << i)) >> i) != ((goal & (1 << i)) >> i): | |
count += 1 | |
return count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment