Set all odd bits of a number

Last Updated : 28 Aug, 2026

Given a positive integer n, set all odd-positioned bits in its binary representation and return the resulting number.

Note: The position of the least significant bit (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
Explanation: Binary representation of 10 is 1010. Setting all odd bits make the number 1111 which is binary representation of 15.

Try It Yourself
redirect icon

[Naive Approach] Using Bit-by-Bit Traversal - O(log n) Time and O(1) Space

We can walk through the bits of n one position at a time,. For every odd position (1st, 3rd, 5th, ...), we set it by doing OR with a mask with that position set.

  • Initialize count = 0 and mask res = 0.
  • Loop while a temporary copy of n is greater than 0.
  • If count is even (representing an odd bit position), set the bit in res via res |= (1 << count).
  • Increment count and right-shift the copy.
  • Return n | res.

For Example: n = 20 (Binary: 10100), initialized with res = 0 and count = 0.

  • Itr 1 (temp = 20): count = 0 is even. Set bit in mask: res |= (1 << 0) = 1 (00001). count becomes 1, temp becomes 10.
  • Itr 2 (temp = 10): count = 1 is odd. Skip. count becomes 2, temp becomes 5.
  • Itr 3 (temp = 5): count = 2 is even. Set bit in mask: res |= (1 << 2) = 4 (00101). count becomes 3, temp becomes 2.
  • Itr 4 (temp = 2): count = 3 is odd. Skip. count becomes 4, temp becomes 1.
  • Itr 5 (temp = 1): count = 4 is even. Set bit in mask: res |= (1 << 4) = 16 (10101). count becomes 5, temp becomes 0.
  • Final Result: Loop ends. Returns n | res (10100 | 10101 = 10101), which equals 21.
C++
#include <iostream>
using namespace std;

// Function to set all odd-positioned bits of n
int setAllOddBits(int n) {

    int count = 0;

    // res stores a mask with only odd
    // positions set, like 0101...
    int res = 0;

    // Walk through the bits of n one at a time
    for (int temp = n; temp > 0; temp >>= 1) {

        // count even means an odd bit position
        if (count % 2 == 0) res |= (1 << count);

        count++;
    }

    return (n | res);
}

int main() {
    int n = 20;
    cout << setAllOddBits(n) << endl;
    return 0;
}
Java
class GFG {

    // Function to set all odd-positioned bits of n
    static int setAllOddBits(int n) {

        int count = 0;

        // res stores a mask with only odd
        // positions set, like 0101...
        int res = 0;

        // Walk through the bits of n one at a time
        for (int temp = n; temp > 0; temp >>= 1) {

            // count even means an odd bit position
            if (count % 2 == 0) res |= (1 << count);

            count++;
        }

        return (n | res);
    }

    public static void main(String[] args) {
        int n = 20;
        System.out.println(setAllOddBits(n));
    }
}
Python
# Function to set all odd-positioned bits of n
def setAllOddBits(n):
    count = 0

    # res stores a mask with only odd
    # positions set, like 0101...
    res = 0

    # Walk through the bits of n one at a time
    temp = n
    while temp > 0:

        # count even means an odd bit position
        if count % 2 == 0:
            res |= (1 << count)

        count += 1
        temp >>= 1

    return n | res

if __name__ == "__main__":
    n = 20
    print(setAllOddBits(n))
C#
using System;

class GFG {

    // Function to set all odd-positioned bits of n
    static int setAllOddBits(int n) {

        int count = 0;

        // res stores a mask with only odd
        // positions set, like 0101...
        int res = 0;

        // Walk through the bits of n one at a time
        for (int temp = n; temp > 0; temp >>= 1) {

            // count even means an odd bit position
            if (count % 2 == 0) res |= (1 << count);

            count++;
        }

        return (n | res);
    }

    public static void Main() {
        int n = 20;
        Console.WriteLine(setAllOddBits(n));
    }
}
JavaScript
// Function to set all odd-positioned bits of n
function setAllOddBits(n) {

    let count = 0;

    // res stores a mask with only odd
    // positions set, like 0101...
    let res = 0;

    // Walk through the bits of n one at a time
    for (let temp = n; temp > 0; temp >>= 1) {

        // count even means an odd bit position
        if (count % 2 === 0) res |= (1 << count);

        count++;
    }

    return (n | res);
}

// Driver Code
let n = 20;
console.log(setAllOddBits(n));

Output
21

[Expected Approach] Using MSB - O(1) Time and O(1) Space

The idea is to first find the most significant bit (MSB) of n, and then build an alternating 0101... pattern of the same bit-length in a handful of operations, without ever looping over individual positions.

Example: n = 20 (Binary: 10100),

  • Step 1 (Isolate MSB): Propagate bits to get 31 (11111), then compute (31 + 1) >> 1 = 16 (10000).
  • Step 2 (Generate Pattern): Apply even right-shifts to 16 (10000 | 00100 | 00001) to form the alternating pattern 10101 (21).
  • Step 3 (Align LSB): The last bit of 10101 is 1, so no extra shift is needed.
  • Step 4 (Final Result): Return n | pattern (10100 | 10101), which equals 21.
C++
#include <iostream>
using namespace std;

// Function to return only the MSB of n set
int getMsb(int n) {

    // Fill in every bit below the MSB
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Isolate just the MSB
    return (n + 1) >> 1;
}

// Function to build an alternating odd-bit
// pattern of the same size as n
int getOddBitsPattern(int n) {
    n = getMsb(n);

    // Spread the MSB into a 1010... pattern
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Make sure the pattern ends at position 1
    if ((n & 1) == 0) n = n >> 1;

    return n;
}

// Function to set all odd-positioned bits of n
int setAllOddBits(int n) {

    // OR n with the odd-bit pattern
    return n | getOddBitsPattern(n);
}

int main() {
    int n = 20;
    cout << setAllOddBits(n) << endl;
    return 0;
}
Java
class GFG {

    // Function to return only the MSB of n set
    static int getMsb(int n) {

        // Fill in every bit below the MSB
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;

        // Isolate just the MSB
        return (n + 1) >> 1;
    }

    // Function to build an alternating odd-bit
    // pattern of the same size as n
    static int getOddBitsPattern(int n) {
        n = getMsb(n);

        // Spread the MSB into a 1010... pattern
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;

        // Make sure the pattern ends at position 1
        if ((n & 1) == 0) n = n >> 1;

        return n;
    }

    // Function to set all odd-positioned bits of n
    static int setAllOddBits(int n) {

        // OR n with the odd-bit pattern
        return n | getOddBitsPattern(n);
    }

    public static void main(String[] args) {
        int n = 20;
        System.out.println(setAllOddBits(n));
    }
}
Python
# Function to return only the MSB of n set
def getMsb(n):

    # Fill in every bit below the MSB
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16

    # Isolate just the MSB
    return (n + 1) >> 1

# Function to build an alternating odd-bit
# pattern of the same size as n
def getOddBitsPattern(n):
    n = getMsb(n)

    # Spread the MSB into a 1010... pattern
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16

    # Make sure the pattern ends at position 1
    if (n & 1) == 0:
        n = n >> 1

    return n

# Function to set all odd-positioned bits of n
def setAllOddBits(n):

    # OR n with the odd-bit pattern
    return n | getOddBitsPattern(n)

if __name__ == "__main__":
    n = 20
    print(setAllOddBits(n))
C#
using System;

class GFG {

    // Function to return only the MSB of n set
    static int getMsb(int n) {

        // Fill in every bit below the MSB
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;

        // Isolate just the MSB
        return (n + 1) >> 1;
    }

    // Function to build an alternating odd-bit
    // pattern of the same size as n
    static int getOddBitsPattern(int n) {
        n = getMsb(n);

        // Spread the MSB into a 1010... pattern
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;

        // Make sure the pattern ends at position 1
        if ((n & 1) == 0) n = n >> 1;

        return n;
    }

    // Function to set all odd-positioned bits of n
    static int setAllOddBits(int n) {

        // OR n with the odd-bit pattern
        return n | getOddBitsPattern(n);
    }

    public static void Main() {
        int n = 20;
        Console.WriteLine(setAllOddBits(n));
    }
}
JavaScript
// Function to return only the MSB of n set
function getMsb(n) {

    // Fill in every bit below the MSB
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Isolate just the MSB
    return (n + 1) >> 1;
}

// Function to build an alternating odd-bit
// pattern of the same size as n
function getOddBitsPattern(n) {
    n = getMsb(n);

    // Spread the MSB into a 1010... pattern
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Make sure the pattern ends at position 1
    if ((n & 1) === 0) n = n >> 1;

    return n;
}

// Function to set all odd-positioned bits of n
function setAllOddBits(n) {

    // OR n with the odd-bit pattern
    return n | getOddBitsPattern(n);
}

// Driver Code
let n = 20;
console.log(setAllOddBits(n));

Output
21

[Alternative Approach] MSB using Leading Zero Count - O(1) Time and O(1) Space

We use a leading-zero count function to find the most significant bit. We then extract just that many lower bits from a pre-computed full-width alternating constant (0x55555555) to build the mask instantly in O(1) time.

  • Compute bitLen, the number of active bits in n, using leading zero counts (32 - leading_zeros).
  • Generate the mask by filtering the alternating constant 0x55555555 to only the lowest bitLen bits using mask = 0x55555555 & ((1 << bitLen) - 1).
  • Return the bitwise OR of n and mask.

For Example, n = 20 (Binary: 10100)

  • Step 1: The number of leading zeros for 20 in a 32-bit integer is 27, giving bitLen = 32 - 27 = 5.
  • Step 2: Compute (1 << 5) - 1 = 31 (11111).
  • Step 3: Extract the mask: 0x55555555 & 31 = 10101 (21).
  • Step 4: Return n | mask (10100 | 10101 = 10101), which equals 21.
C++
#include <iostream>
using namespace std;

int setAllOddBits(int n) {
    int bitLen = 32 - __builtin_clz(n);
    int mask = 0x55555555 & ((1 << bitLen) - 1);
    return n | mask;
}

int main() {
    int n = 20;
    cout << setAllOddBits(n) << endl;
    return 0;
}
Java
class GFG {
    static int setAllOddBits(int n) {
        int bitLen = 32 - Integer.numberOfLeadingZeros(n);
        int mask = 0x55555555 & ((1 << bitLen) - 1);
        return n | mask;
    }

    public static void main(String[] args) {
        int n = 20;
        System.out.println(setAllOddBits(n));
    }
}
Python
def setAllOddBits(n: int) -> int:
    bitLen = n.bit_length()
    mask = 0x55555555 & ((1 << bitLen) - 1)
    return n | mask

if __name__ == "__main__":
    n = 20
    print(setAllOddBits(n))
C#
using System;

class GFG {
    static int setAllOddBits(int n) {
        // Find the bit-length of n using a simple loop
        int bitLen = 0;
        int temp = n;
        while (temp > 0) {
            bitLen++;
            temp >>= 1;
        }
        
        // Mask with all odd positions set, restricted to lowest bitLen bits
        int mask = 0x55555555 & ((1 << bitLen) - 1);
        return n | mask;
    }

    public static void Main() {
        int n = 20;
        Console.WriteLine(setAllOddBits(n));
    }
}
JavaScript
function setAllOddBits(n) {
    let bitLen = 32 - Math.clz32(n);
    let mask = 0x55555555 & ((1 << bitLen) - 1);
    return n | mask;
}

let n = 20;
console.log(setAllOddBits(n));

Output
21
Comment