Skip to content

Commit 8046044

Browse files
add a solution for 461
1 parent 132ec47 commit 8046044

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,22 @@ public int hammingDistance(int x, int y) {
1212
return count;
1313
}
1414
}
15+
16+
public static class Solution2 {
17+
public int hammingDistance(int x, int y) {
18+
int ans = 0;
19+
for (int i = 0; i < 32; i++) {
20+
ans += (x & 1) ^ (y & 1);
21+
x >>= 1;
22+
y >>= 1;
23+
}
24+
return ans;
25+
}
26+
}
27+
28+
public static class Solution3 {
29+
public int hammingDistance(int x, int y) {
30+
return Integer.bitCount(x ^ y);
31+
}
32+
}
1533
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._461;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _461Test {
10+
private static _461.Solution1 solution1;
11+
private static _461.Solution2 solution2;
12+
private static _461.Solution3 solution3;
13+
private static int x;
14+
private static int y;
15+
private static int expected;
16+
17+
@BeforeClass
18+
public static void setup() {
19+
solution1 = new _461.Solution1();
20+
solution2 = new _461.Solution2();
21+
solution3 = new _461.Solution3();
22+
}
23+
24+
@Test
25+
public void test1() {
26+
x = 1;
27+
y = 4;
28+
expected = 2;
29+
assertEquals(expected, solution1.hammingDistance(x, y));
30+
assertEquals(expected, solution2.hammingDistance(x, y));
31+
assertEquals(expected, solution3.hammingDistance(x, y));
32+
}
33+
34+
@Test
35+
public void test2() {
36+
x = 3;
37+
y = 1;
38+
expected = 1;
39+
assertEquals(expected, solution1.hammingDistance(x, y));
40+
assertEquals(expected, solution2.hammingDistance(x, y));
41+
assertEquals(expected, solution3.hammingDistance(x, y));
42+
}
43+
44+
}

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