Bit Manipulation Tricks
Bit Manipulation Tricks
python
Copy code
if (n & 1) == 1:
# n is odd
python
Copy code
if (n & 1) == 0:
# n is even
Using XOR:
python
Copy code
a=a^b
b=a^b
a=a^b
A number NNN is a power of two if it has only one bit set (i.e., only one
1 in its binary representation).
python
Copy code
def is_power_of_two(n):
Use the n & (n - 1) trick to clear the lowest set bit in each iteration.
python
Copy code
def count_set_bits(n):
count = 0
while n:
count += 1
return count
python
Copy code
flipped = ~n
python
Copy code
lowest_set_bit = n & -n
This trick works because -n is the two's complement, which flips all bits
up to the lowest set bit.
python
Copy code
n = n & (n - 1)
To set the kkk-th bit (0-based index from the right), use:
python
Copy code
n = n | (1 << k)
python
Copy code
python
Copy code
n = n ^ (1 << k)
python
Copy code
python
Copy code
rightmost_one = n & -n
13. Rounding Up to the Next Power of Two
python
Copy code
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
This works by propagating the highest set bit to all lower positions,
then adding 1.
python
Copy code
def msb_position(n):
pos = -1
while n:
pos += 1
n >>= 1
return pos
python
Copy code
result = 0
for _ in range(bit_size):
n >>= 1
return result
python
Copy code
def generate_subsets(arr):
n = len(arr)
subsets = []
subset = []
for j in range(n):
subset.append(arr[j])
subsets.append(subset)
return subsets
python
Copy code
def swap_even_odd_bits(n):
python
Copy code
You can check if two numbers xxx and yyy have opposite signs by:
python
Copy code
return (x ^ y) < 0
This works because the XOR of a positive and a negative number will
have the sign bit set.
python
Copy code
def count_leading_zeros(n):
count = 0
count += 1
n <<= 1
return count
4o