-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathOstenHun.cpp
More file actions
51 lines (42 loc) ยท 1.29 KB
/
OstenHun.cpp
File metadata and controls
51 lines (42 loc) ยท 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
191. Number of 1 Bits
Given a positive integer n, write a function
that returns the number of set bits in its binary representation
(also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Constraints:
1 <= n <= 2^31 - 1
*/
// ๋นํธ ์ฐ์ฐ์ ์ด์ฉํ์ฌ ํ๊ธฐ
#include <iostream>
using namespace std;
// ์๊ฐ ๋ณต์ก๋ : O(logn) -> n >> 1 ์ฐ์ฐ์ ํ๊ธฐ ๋๋ฌธ์ ์ ๋ฐ์ฉ ์ค์ด๋ฌ
// ๋ฌธ์ ์ ์กฐ๊ฑด์ 32bit ๋ด์ ๋ฒ์์ด๊ธฐ ๋๋ฌธ์ 32๋ฒ์ ๋ฐ๋ณต์ผ๋ก ํญ์ ๋๋๊ธฐ์ O(1)์ด๋ผ๊ณ ํ ์ ์๋ค.
// ๊ณต๊ฐ ๋ณต์ก๋ : O(1)
class Solution {
public:
int hammingweight(int n) {
unsigned int answer = 0;
while(n>0) {
if (n & 1)
answer++;
n = n >> 1;
}
// ์ฒ์ ํ์๋ ํ์ด.
// unsigned int answer = 0;
// for (int i = 0; i < 32; i++) {
// if ((n >> i) & 1) answer++;
// }
// ์๊ฐ ๋ชป ํ ํ์ด
// -> n & (n-1) ์ ํ๋ฉด ๊ฐ์ฅ ์ค๋ฅธ์ชฝ 1๋นํธ๋ฅผ ์ง์ด๋ค.
// while (n > 0) {
// n &= (n - 1);
// answer++;
// }
return answer;
}
};