Skip to content

Commit 19b4c0b

Browse files
refactor 89
1 parent d60dbc3 commit 19b4c0b

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/main/java/com/fishercoder/solutions/_89.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,31 @@ public List<Integer> grayCode(int n) {
3939
}
4040
}
4141

42+
public static class Solution2 {
43+
public List<Integer> grayCode(int n) {
44+
List<Integer> result = new ArrayList();
45+
for (int i = 0; i < Math.pow(2, n); i++) {
46+
result.add(i ^ (i >> 1));
47+
}
48+
return result;
49+
}
50+
}
51+
52+
public static void main (String... args) {
53+
System.out.println("-----------------------------------------------------------------------------------------");
54+
System.out.println("How to understand i << n? It means n to the power of two, see below. So we have an equivalent solution, which is solution2.");
55+
System.out.println("1 << 2: " + (1 << 2));
56+
System.out.println("1 << 3: " + (1 << 3));
57+
System.out.println("1 << 4: " + (1 << 4));
58+
System.out.println("1 << 5: " + (1 << 5));
59+
System.out.println("1 << 6: " + (1 << 6));
60+
System.out.println("-----------------------------------------------------------------------------------------");
61+
System.out.println("How to understand i >> 1? It means to shift the number i to the right by 1 bit, see below");
62+
System.out.println("2 >> 1: " + (2 >> 1));
63+
System.out.println("3 >> 1: " + (3 >> 1));
64+
System.out.println("4 >> 1: " + (4 >> 1));
65+
System.out.println("5 >> 1: " + (5 >> 1));
66+
System.out.println("6 >> 1: " + (6 >> 1));
67+
}
68+
4269
}

src/test/java/com/fishercoder/_89Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,17 @@
1010
public class _89Test {
1111

1212
private static _89.Solution1 solution1;
13+
private static _89.Solution2 solution2;
1314

1415
@BeforeClass
1516
public static void setup() {
1617
solution1 = new _89.Solution1();
18+
solution2 = new _89.Solution2();
1719
}
1820

1921
@Test
2022
public void test1() {
2123
assertEquals(Arrays.asList(0, 1, 3, 2, 6, 7, 5, 4), solution1.grayCode(3));
24+
assertEquals(Arrays.asList(0, 1, 3, 2, 6, 7, 5, 4), solution2.grayCode(3));
2225
}
2326
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy