Skip to content

Instantly share code, notes, and snippets.

@happyWinner
Created July 27, 2014 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyWinner/14099aebd3d63a6a380f to your computer and use it in GitHub Desktop.
Save happyWinner/14099aebd3d63a6a380f to your computer and use it in GitHub Desktop.
/**
* Write a program to swap odd and even bits in an integer with as few instructions as possible
* (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).
*
* Time Complexity: O(1)
* Space Complexity: O(1)
*/
public class Question5_6 {
public int swapBits(int value) {
return ((value & 0x55555555) << 1) | ((value & 0xAAAAAAAA) >> 1);
}
public static void main(String[] args) {
Question5_6 question5_6 = new Question5_6();
System.out.println(Integer.toBinaryString(question5_6.swapBits(0b1100)));
System.out.println(Integer.toBinaryString(question5_6.swapBits(0b1110)));
System.out.println(Integer.toBinaryString(question5_6.swapBits(0b1010)));
System.out.println(Integer.toBinaryString(question5_6.swapBits(0)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment