Skip to content

Commit 55d5bd9

Browse files
committed
Bit swap done
1 parent f4f0a17 commit 55d5bd9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.ctci.bitmanipulation;
2+
3+
/**
4+
* @author rampatra
5+
* @since 2019-03-18
6+
*/
7+
public class PairwiseSwap {
8+
9+
/**
10+
* Write a program to swap odd and even bits in an integer with as few instructions as
11+
* possible (e.g., bit O and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).
12+
*
13+
* Approach:
14+
* Shift the odd bits to the left, shift the even bits to the right, and finally, OR both the results.
15+
* Note: You can operate on only odd bits or only even bits by using the appropriate masks, for e.g.,
16+
* 0x55555555 for odd bits and 0xaaaaaaaa for even bits.
17+
*
18+
* @param n an input integer.
19+
* @return an integer with even and odd bits swapped.
20+
*/
21+
private static int swapBits(int n) {
22+
return ((n & 0x55555555) << 1) | ((n & 0xaaaaaaaa) >>> 1);
23+
}
24+
25+
public static void main(String[] args) {
26+
System.out.println("Input: " + Integer.toBinaryString(1569) +
27+
"\nOutput: " + Integer.toBinaryString(swapBits(1569)));
28+
29+
assert Integer.toBinaryString(swapBits(1569)).equals("100100010010");
30+
31+
System.out.println("Input: " + Integer.toBinaryString(2680) +
32+
"\nOutput: " + Integer.toBinaryString(swapBits(2680)));
33+
34+
assert Integer.toBinaryString(swapBits(2680)).equals("10110110100");
35+
36+
// fyi
37+
System.out.println(Integer.toBinaryString(0xaaaaaaaa));
38+
System.out.println(Integer.toBinaryString(0x99999999));
39+
}
40+
}

0 commit comments

Comments
 (0)