Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Created October 29, 2020 20:20
Show Gist options
  • Save Ch-sriram/8d80fa1527322119c93faf3f06aabe4f to your computer and use it in GitHub Desktop.
Save Ch-sriram/8d80fa1527322119c93faf3f06aabe4f to your computer and use it in GitHub Desktop.
Swap All Odd & Even Bits [TC: O(logN); SC: O(1)]
// Problem Link: https://practice.geeksforgeeks.org/problems/swap-all-odd-and-even-bits-1587115621/1/
unsigned int swapBits(unsigned int n) {
for(uint32_t i = 0; i < 32; i += 2) {
uint32_t requiredBits = ((n >> i) & 3) ^ 3;
if(requiredBits == 1 || requiredBits == 2)
n ^= (3 << i);
}
return n;
}
@Ch-sriram
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment