Skip to content

Commit

Permalink
CTCI 5.07: PairwiseSwap.groovy
Browse files Browse the repository at this point in the history
  • Loading branch information
Pap Lőrinc committed Feb 27, 2016
1 parent 229599d commit 9f294cf
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/main/groovy/Ch05_BitManipulation/_05_07_PairwiseSwap.groovy
Original file line number Diff line number Diff line change
@@ -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)
}
}
Original file line number Diff line number Diff line change
@@ -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*/
}

0 comments on commit 9f294cf

Please sign in to comment.