![]() |
VOOZH | about |
Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators
If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).
Note: If the bit would be already set then it would remain unchanged.
6
Time Complexity: O(1)
Auxiliary Space: O(1)
We have passed the parameter by 'call by reference' to make permanent changes in the number.
Suppose we want to unset a bit at nth position in number 'num' then we have to do this with the help of 'AND' (&) operator.
5
Time Complexity: O(1)
Auxiliary Space: O(1)
Toggling means to turn bit 'on'(1) if it was 'off'(0) and to turn 'off'(0) if it was 'on'(1) previously. We will be using the 'XOR' operator here which is this '^'. The reason behind the 'XOR' operator is because of its properties.
6
Time Complexity: O(1)
Auxiliary Space: O(1)
It is quite easily doable using the 'AND' operator.
1
Time Complexity: O(1)
Auxiliary Space: O(1)
Observe that we have first left shifted '1' and then used 'AND' operator to get bit at that position. So if there is '1' at position 'pos' in 'num', then after 'AND' our variable 'bit' will store '1' else if there is '0' at position 'pos' in the number 'num' than after 'AND' our variable bit will store '0'.
Some more quick hacks:
This is also the '1s complement of number'.
-5
Time Complexity: O(1)
Auxiliary Space: O(1)
So formally we can have 2's complement by finding 1s complement and adding 1 to the result i.e (~num+1) or what else we can do is using '-' operator.
This is two's complement -4 This is also two's complement -4
Time Complexity: O(1)
Auxiliary Space: O(1)
In many situations we want to strip off the lowest set bit for example in Binary Indexed tree data structure, counting number of set bit in a number. We do something like this:
X = X & (X-1)
But how does it even work? Let us see this by taking an example, let X = 1100.
6
Time Complexity: O(1)
Auxiliary Space: O(1)
This is done by using the expression 'X &(-X)'Let us see this by taking an example: Let X = 00101100. So ~X(1's complement) will be '11010011' and 2's complement will be (~X+1 or -X) i.e. '11010100'.So if we 'AND' original number 'X' with its two's complement which is '-X', we get the lowest set bit.
00101100 & 11010100 ----------- 00000100
2
Time Complexity: O(1)
Auxiliary Space: O(1)
Division by 2 and Multiplication by 2 are very frequently that too in loops in Competitive Programming so using Bitwise operators can help in speeding up the code.
Divide by 2 using the right shift operator:
00001100 >> 1 (00001100 is 12) ------------ 00000110 (00000110 is 6)
6
Time Complexity: O(1)
Auxiliary Space: O(1)
Multiply by 2 using the left shift operator:
00001100 << 1 (00001100 is 12) ------------ 00011000 (00000110 is 24)
24
Time Complexity: O(1)
Auxiliary Space: O(1)
Bit Tricks for Competitive Programming
Refer BitWise Operators Articles for more articles on Bit Hacks.