blob: b282e9d096ce37a6d812b436e8cebfbdd4a71873 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package theweeklychallenge;
/*
Week 192:
https://theweeklychallenge.org/blog/perl-weekly-challenge-192
Task #1: Binary Flip
You are given a positive integer, $n.
Write a script to find the binary flip.
Compile and Run:
mohammad-anwar/java$ javac theweeklychallenge/BinaryFlip.java
mohammad-anwar/java$ java theweeklychallenge.BinaryFlip
*/
import junit.framework.TestCase;
import static junit.framework.Assert.*;
public class BinaryFlip extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(
theweeklychallenge.BinaryFlip.class
);
}
public void testBinaryFlip() {
assertEquals(2, binaryFlip(5));
assertEquals(3, binaryFlip(4));
assertEquals(1, binaryFlip(6));
}
public static int binaryFlip(int n) {
String[] bits = Integer.toBinaryString(n).split("");
String flipped = "";
for(String bit : bits) {
flipped += (bit.equals("0")) ? '1' : '0';
}
return Integer.parseInt(flipped, 2);
}
}
|