![]() |
VOOZH | about |
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).
Table of Content
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:
43
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:
43