diff --git a/src/main/groovy/Ch05_BitManipulation/_05_07_PairwiseSwap.groovy b/src/main/groovy/Ch05_BitManipulation/_05_07_PairwiseSwap.groovy new file mode 100644 index 0000000..2083ba3 --- /dev/null +++ b/src/main/groovy/Ch05_BitManipulation/_05_07_PairwiseSwap.groovy @@ -0,0 +1,10 @@ +package Ch05_BitManipulation + +/** Determine the number of different bits in two numbers */ +class _05_07_PairwiseSwap { + /** Complexity: O(1) */ + private static ODD_MASK = 0b01010101_01010101_01010101_01010101 + static swapOddEvenBits(int num) { + ((num >> 1) & ODD_MASK) | ((num & ODD_MASK) << 1) + } +} diff --git a/src/test/groovy/Ch05_BitManipulation/_05_07_PairwiseSwapTest.groovy b/src/test/groovy/Ch05_BitManipulation/_05_07_PairwiseSwapTest.groovy new file mode 100644 index 0000000..5c21235 --- /dev/null +++ b/src/test/groovy/Ch05_BitManipulation/_05_07_PairwiseSwapTest.groovy @@ -0,0 +1,33 @@ +package Ch05_BitManipulation + +import spock.lang.Specification +import spock.lang.Unroll + +import static Ch05_BitManipulation._05_07_PairwiseSwap.swapOddEvenBits + +@Unroll class _05_07_PairwiseSwapTest extends Specification { + /*@formatter:off*/ + def 'swap #source == #target?'() { + expect: swapOddEvenBits(source) == target + where: source || target + 0b0000 || 0b0000 + 0b0001 || 0b0010 + 0b0010 || 0b0001 + 0b0011 || 0b0011 + 0b0100 || 0b1000 + 0b0101 || 0b1010 + 0b0110 || 0b1001 + 0b0111 || 0b1011 + 0b1000 || 0b0100 + 0b1001 || 0b0110 + 0b1010 || 0b0101 + 0b1011 || 0b0111 + 0b1100 || 0b1100 + 0b1101 || 0b1110 + 0b1110 || 0b1101 + 0b1111 || 0b1111 + + 0b1001010101001010 || 0b0110101010000101 + } + /*@formatter:on*/ +}