Created
July 27, 2014 05:54
-
-
Save WOLOHAHA/ccdc3bf4f78cecf8ca50 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! are swapped, bit 2 and bit 3 are swapped, and so on).
This file contains hidden or 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
| package POJ; | |
| public class Main{ | |
| /** | |
| * | |
| * 5.6 Write a program to swap odd and even bits in an integer with as few instructions | |
| * as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and so on). | |
| * | |
| * | |
| */ | |
| public static void main(String[] args) { | |
| Main so = new Main(); | |
| System.out.println(so.swapBits(4)); | |
| } | |
| public int swapBits(int n){ | |
| return (((n&0xaaaaaaaa)>>1)|((n&0x55555555)<<1)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment