Skip to content

Commit ee34534

Browse files
refactor 476
1 parent 3407f4c commit ee34534

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed
Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 476. Number Complement
5+
*
46
* Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
57
68
Note:
@@ -17,21 +19,25 @@
1719
*/
1820
public class _476 {
1921

20-
public int findComplement_oneLiner(int num) {
21-
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
22+
public static class Solution1 {
23+
public int findComplement(int num) {
24+
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
25+
}
2226
}
2327

24-
public int findComplement(int num) {
25-
String str = Integer.toBinaryString(num);
26-
StringBuilder sb = new StringBuilder();
27-
char[] chars = str.toCharArray();
28-
for (int i = 0; i < chars.length; i++) {
29-
if (chars[i] == '0') {
30-
sb.append("1");
31-
} else {
32-
sb.append("0");
28+
public static class Solution2 {
29+
public int findComplement(int num) {
30+
String str = Integer.toBinaryString(num);
31+
StringBuilder sb = new StringBuilder();
32+
char[] chars = str.toCharArray();
33+
for (int i = 0; i < chars.length; i++) {
34+
if (chars[i] == '0') {
35+
sb.append("1");
36+
} else {
37+
sb.append("0");
38+
}
3339
}
40+
return Integer.parseInt(sb.toString(), 2);
3441
}
35-
return Integer.parseInt(sb.toString(), 2);
3642
}
3743
}

src/test/java/com/fishercoder/_476Test.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,16 @@
1111
* Created by fishercoder on 1/14/17.
1212
*/
1313
public class _476Test {
14-
private static _476 test;
14+
private static _476.Solution1 solution1;
15+
private static _476.Solution2 solution2;
1516
private static int expected;
1617
private static int actual;
1718
private static int input;
1819

1920
@BeforeClass
2021
public static void setup() {
21-
test = new _476();
22+
solution1 = new _476.Solution1();
23+
solution2 = new _476.Solution2();
2224
}
2325

2426
@Before
@@ -33,7 +35,8 @@ public void test1() {
3335

3436
input = 5;
3537
expected = 2;
36-
actual = test.findComplement(input);
38+
actual = solution1.findComplement(input);
39+
actual = solution2.findComplement(input);
3740
assertEquals(expected, actual);
3841

3942
}
@@ -43,7 +46,8 @@ public void test2() {
4346

4447
input = 5;
4548
expected = 2;
46-
actual = test.findComplement_oneLiner(input);
49+
actual = solution1.findComplement(input);
50+
actual = solution2.findComplement(input);
4751
assertEquals(expected, actual);
4852

4953
}

0 commit comments

Comments
 (0)