Skip to main content

3 posts tagged with "Bit Manipulation"

View All Tags

· One min read
class Solution1:
def getSum(self, a: int, b: int) -> int:
MASK, xor, carry = 1023, a ^ b, (a & b) << 1
if carry & MASK:
return self.getSum(xor, carry)
return xor & MASK if carry else xor


class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 1023
while b & MASK:
a, b = a ^ b, (a & b) << 1
return a & MASK if b else a

· One min read
class Solution1:
def minFlips(self, a: int, b: int, c: int) -> int:
def flip_last_bits(numbers: tuple[int, ...]):
a, b, c = (n & 1 for n in numbers)
return 2 if (a + b, c) == (2, 0) else int(a + b + c == 1)

result, numbers = 0, (a, b, c)
while any(numbers):
result += flip_last_bits(numbers)
numbers = tuple(n >> 1 for n in numbers)
return result


class Solution2:
def minFlips(self, a: int, b: int, c: int) -> int:
def count(n):
return bin(n).count('1')

return count((a | b) ^ c) + count(a & b & ~c)