![]() |
VOOZH | about |
Given a number, the task is to set all even bits of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). The position of LSB is considered as 1.
Examples :
Input : 20 Output : 30 Binary representation of 20 is 10100. After setting even bits, we get 11110 Input : 10 Output : 10
Method 1:
Let’s understand this approach with the below code.
10
Method 2 (A O(1) solution for 32 bit numbers)
10
Method 3: Using bit mask
To set a bit, we can take OR of 1 and that bit (as 1 | 1 = 1, and 1 | 0 = 1). Therefore, to set all odd bits of an n-bit number, we need to use a bit mask which is an n-bit binary number with all odd bits set. This mask can be generated in 1 step using the formula of sum of a geometric progression, as an n bit number ...1010 is equal to 21 + 23 + 25 + .... 2 (n - !(n % 1)) .
Approach:
110315
Time Complexity: O(1)
Auxiliary Space: O(1)