File tree 2 files changed +26
-16
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder 2 files changed +26
-16
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
/**
4
+ * 476. Number Complement
5
+ *
4
6
* Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
5
7
6
8
Note:
17
19
*/
18
20
public class _476 {
19
21
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
+ }
22
26
}
23
27
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
+ }
33
39
}
40
+ return Integer .parseInt (sb .toString (), 2 );
34
41
}
35
- return Integer .parseInt (sb .toString (), 2 );
36
42
}
37
43
}
Original file line number Diff line number Diff line change 11
11
* Created by fishercoder on 1/14/17.
12
12
*/
13
13
public class _476Test {
14
- private static _476 test ;
14
+ private static _476 .Solution1 solution1 ;
15
+ private static _476 .Solution2 solution2 ;
15
16
private static int expected ;
16
17
private static int actual ;
17
18
private static int input ;
18
19
19
20
@ BeforeClass
20
21
public static void setup () {
21
- test = new _476 ();
22
+ solution1 = new _476 .Solution1 ();
23
+ solution2 = new _476 .Solution2 ();
22
24
}
23
25
24
26
@ Before
@@ -33,7 +35,8 @@ public void test1() {
33
35
34
36
input = 5 ;
35
37
expected = 2 ;
36
- actual = test .findComplement (input );
38
+ actual = solution1 .findComplement (input );
39
+ actual = solution2 .findComplement (input );
37
40
assertEquals (expected , actual );
38
41
39
42
}
@@ -43,7 +46,8 @@ public void test2() {
43
46
44
47
input = 5 ;
45
48
expected = 2 ;
46
- actual = test .findComplement_oneLiner (input );
49
+ actual = solution1 .findComplement (input );
50
+ actual = solution2 .findComplement (input );
47
51
assertEquals (expected , actual );
48
52
49
53
}
You can’t perform that action at this time.
0 commit comments