Skip to content

Commit e92b934

Browse files
committed
Solution for Number of 1 Bits #232
1 parent 7ff138e commit e92b934

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

number-of-1-bits/dohyeon2.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.HashMap;
2+
3+
class Solution {
4+
// n & (n-1) -> 마지막 set bit 제거
5+
// n & -n -> 마지막 set bit 추출
6+
// i >> 1 -> 절반
7+
// i & 1 -> 마지막 bit
8+
// i & (i - 1) == 0 -> i는 2의 거듭제곱
9+
10+
// Follow up: If this function is called many times, how would you optimize it?
11+
// I'll cache the results in a HashMap.
12+
// (Or I can use lookup table or DP)
13+
private HashMap<Integer, Integer> cache = new HashMap<>();
14+
15+
public int hammingWeight(int n) {
16+
// simple in Java
17+
// return Integer.bitCount(n);
18+
19+
if (cache.containsKey(n)) {
20+
return cache.get(n);
21+
}
22+
23+
int buffer = n;
24+
int answer = 0;
25+
26+
// 1. self thought solution
27+
// TC : O(log n)
28+
// SC : O(1)
29+
while (buffer > 0) {
30+
answer += buffer % 2;
31+
buffer = buffer / 2;
32+
}
33+
34+
// 2. fancy solution from leetcode using bit computing
35+
// TC : O(log n)
36+
// SC : O(1)
37+
// while(buffer > 0){
38+
// if((buffer & 1) == 1){
39+
// answer++;
40+
// }
41+
// buffer = buffer >> 1;
42+
// }
43+
44+
// 3. another fancy solution from ChatGPT
45+
// Brian Kernighan algorithm
46+
// TC : O(number of set bits)
47+
// SC : O(1)
48+
// while (buffer != 0) {
49+
// // 11 & 10 => 1 & 0 => 0
50+
// buffer = buffer & (buffer - 1); // AND with buffer and buffer -1 => remove
51+
// last set bit.
52+
// System.out.println(buffer);
53+
// answer++;
54+
// }
55+
56+
// 4. using lookup table
57+
// int[] table = new int[256];
58+
// for (int i = 0; i < 256; i++) {
59+
// table[i] = (i & 1) + table[i >> 1];
60+
// }
61+
// answer = table[buffer & 0xff] +
62+
// table[(buffer >> 8) & 0xff] +
63+
// table[(buffer >> 16) & 0xff] +
64+
// table[(buffer >> 24) & 0xff];
65+
66+
// 5. DP
67+
// int[] bits = new int[n + 1];
68+
// for (int i = 1; i <= n; i++) {
69+
// bits[i] = bits[i >> 1] + (i & 1);
70+
// }
71+
72+
cache.put(n, answer);
73+
return answer;
74+
}
75+
}

0 commit comments

Comments
 (0)