VOOZH about

URL: https://www.geeksforgeeks.org/dsa/swap-all-odd-and-even-bits/

⇱ Swap all odd and even bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Swap all odd and even bits

Last Updated : 30 Aug, 2025

Given an unsigned integer n. The task is to swap all odd bits with adjacent even bits.

Examples: 

Input: 23
Output: 43
Explanation: 23 (0010111) should be converted to 43 (0101011).

Input: 2
Output: 1
Explanation: 2 (0010) should be converted to 1 (0001).

[Naive Approach] Time O(1) and Space O(1)

For every even index i in the binary representation of N starting from index 0 swap bits with (i+1)th index.

Follow the steps below to implement the idea:

  • Find the bit at i and i+1 index.
  • To swap the bits subtract and add corresponding values.
  • To remove bit at ith bit to i+1. subtract i_bit<<i and add it at i+1 index for that we need to add i_bit<<(i+1).
  • Similarly subtract (i+1)th bit and add it to ith index.

Output
43

[Efficient Approach] Time O(1) and Space O(1)

The value even_bits obtained by even bits of N and Right shifted (>>) by 1 on even_bits and similarly obtain value odd_bits of odd bits of N and perform left shift (<<) by 1 operation on odd_bits. Now (odd_bits |even_bits) will give the desired value.

Follow the below steps to implement the approach:

  • Initialize variable even_bits with bitwise and of N with 0xAAAAAAAA(32 bit number with all even bits set as 1 and all odd bits as 0). 
  • Initialize variable odd_bits with bitwise and of N with 0x55555555. The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0
  • Right shift even_bits by 1 and Left shift odd_bits by 1. 
  • Return or of even_bits with odd_bits 

Output
43
Comment
Article Tags:
Article Tags: