VOOZH about

URL: https://www.geeksforgeeks.org/dsa/set-odd-bits-number/

⇱ Set all odd bits of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Set all odd bits of a number

Last Updated : 26 Apr, 2023

Given a number, the task is to set all odd bits of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1.

Examples : 

Input : 20
Output : 21
Explanation : Binary representation of 20
is 10100. Setting all odd
bits make the number 10101 which is binary
representation of 21.

Input : 10
Output : 15
Recommended Practice

Method 1 (Using OR) 
1. First generate a number that contains odd position bits. 
2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1.

Let’s understand this approach with below code.  


Output
15


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


Output
15

Another approach:

O(1) approach which supports even long long (64-bit).


Output
15

Time complexity: O(1)

Space complexity: O(1)

Another Approach:

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 ...0101 is equal to 20 + 22 + 24 + .... 2 (n - 1 - !(n % 1)) .


Output
15

Time complexity: O(1)

Space complexity: O(1)

Comment
Article Tags:
Article Tags: