-
-
Save happyWinner/14099aebd3d63a6a380f to your computer and use it in GitHub Desktop.
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
/** | |
* 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