Skip to content

Commit c055eff

Browse files
committed
Refine number-of-1-bits solution
1 parent cd02770 commit c055eff

1 file changed

Lines changed: 17 additions & 8 deletions

File tree

โ€Žnumber-of-1-bits/OstenHun.cppโ€Ž

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
#include <iostream>
2121
using namespace std;
2222

23+
// ์‹œ๊ฐ„ ๋ณต์žก๋„ : O(logn) -> n >> 1 ์—ฐ์‚ฐ์„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ ˆ๋ฐ˜์”ฉ ์ค„์–ด๋“ฌ
24+
// ๋ฌธ์ œ์˜ ์กฐ๊ฑด์€ 32bit ๋‚ด์˜ ๋ฒ”์œ„์ด๊ธฐ ๋•Œ๋ฌธ์— 32๋ฒˆ์˜ ๋ฐ˜๋ณต์œผ๋กœ ํ•ญ์ƒ ๋๋‚˜๊ธฐ์— O(1)์ด๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.
25+
// ๊ณต๊ฐ„ ๋ณต์žก๋„ : O(1)
2326
class Solution {
2427
public:
2528
int hammingweight(int n) {
@@ -29,14 +32,20 @@ class Solution {
2932
answer++;
3033
n = n >> 1;
3134
}
35+
36+
// ์ฒ˜์Œ ํ’€์—ˆ๋˜ ํ’€์ด.
37+
// unsigned int answer = 0;
38+
// for (int i = 0; i < 32; i++) {
39+
// if ((n >> i) & 1) answer++;
40+
// }
41+
42+
// ์ƒ๊ฐ ๋ชป ํ•œ ํ’€์ด
43+
// -> n & (n-1) ์„ ํ•˜๋ฉด ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ 1๋น„ํŠธ๋ฅผ ์ง€์šด๋‹ค.
44+
// while (n > 0) {
45+
// n &= (n - 1);
46+
// answer++;
47+
// }
48+
3249
return answer;
3350
}
3451
};
35-
36-
int main() {
37-
int n;
38-
cin >> n;
39-
Solution s;
40-
41-
cout << s.hammingweight(n);
42-
}

0 commit comments

Comments
ย (0)