VOOZH about

URL: https://www.geeksforgeeks.org/dsa/set-all-even-bits-of-a-number/

⇱ Set all even bits of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Set all even bits of a number

Last Updated : 21 Nov, 2022

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:

  1. First, generate a number that contains even position bits. 
  2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1.

Let’s understand this approach with the below code.


Output
10

Method 2 (A O(1) solution for 32 bit numbers) 


Output
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:

  1. Calculate the number of bits using log2(number)
  2. Calculate the largest power m, of the GP series using the formula  (numOfBits - !(numOfBits % 1)).
  3. Calculate the value of the mask using the formula:  a × (r m + 1 - 1) / (r - 1).
  4. Perform the setting operation using number | mask.

Output
110315

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: