Created
May 30, 2020 05:30
-
-
Save Ch-sriram/db50671bc159a3724d8b8318a58ab226 to your computer and use it in GitHub Desktop.
Given an integer N, swap the adjacent bits in the binary representation of the integer, and print the new number formed after swapping.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
#define ui uint32_t | |
ui swap_bits(ui n) { | |
ui bitval; | |
for(int i = 0; i < 32; i+=2) { | |
bitval = ((n>>i)&1) | (((n>>(i+1))&1)<<1); | |
// for only 01 and 10 => bitval == 1, or bitval == 2. We don't care if bits at adjacent placs are 00 or 11. | |
if(bitval > 0 && bitval < 3) | |
n ^= ((1U<<i) | (1U<<(i+1))); // xor n's value with 11 at the respective position. | |
// same as above: n ^= (3<<i); | |
} | |
return n; | |
} | |
int main() { | |
ui t; cin >> t; | |
while(t--) { | |
ui n; cin >> n; | |
cout << swap_bits(n) << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment