Bitwise Operations Flashcards

1
Q

What is the result of x & (x - 1)?

A

Clears the lowest set bit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you check if a number is a power of 2 using bitwise operations?

A

n & (n - 1) == 0 for n > 0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you swap two numbers using XOR?

A

a = a ^ b; b = a ^ b; a = a ^ b;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you find the single non-duplicate number in an array using XOR?

A

XOR all numbers; duplicates cancel out.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of a bitmask?

A

Representing subsets, toggling bits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you find common bits? Or how do you return 1 if both bits are 1?

A

& AND operation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you find the bitwise & of a range? Why does this work?

A

Shift both numbers right until they are equal, counting shifts. Then shift the result left. This works because numbers sharing a common prefix will retain it, while differing prefixes result in all 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you accumulate bits that have appeared twice? Or compare two bits and return 1 if either is 1?

A

|OR operation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you toggle bits (exclusive or)? Or remove duplicates?

A

^ XOR operation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you invert all bits?

A

~ NOT operation. Flips all bits, and due to two’s complement, ~x is equivalent to -(x+1).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you shift bits to the left?

A

Left shift («), effectively multiplying by 2 for each shift.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you use bitwise operators to find a single digit in an array with others appearing three times?

A

Use ones, twos, and threes variables to track bit appearances.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you check if a number is odd or even using bitwise operations?

A

If n & 1 == 0, then n is even
If n & 1 == 1, then n is odd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly