Bit Manipulation Flashcards

(1 cards)

1
Q

Implement

Bit Inversion
Input: x as int
Output: inverted x

print(f”Original: {bin(x)}”)
print(f”Inverted: {bin(invert(x))}”)

A
def invert(x):
    n = x.bit_length() if x >= 0 else (~x).bit_length()
    mask = (1 << n) - 1
    return x ^ mask

print(f"Original:  {bin(x)}")
print(f"Inverted:  {bin(invert(x)}")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly