-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Pap Lőrinc
committed
Feb 27, 2016
1 parent
229599d
commit 9f294cf
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
10 changes: 10 additions & 0 deletions
10
src/main/groovy/Ch05_BitManipulation/_05_07_PairwiseSwap.groovy
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
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) | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
src/test/groovy/Ch05_BitManipulation/_05_07_PairwiseSwapTest.groovy
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
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*/ | ||
} |