We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c9df170 commit cd02770Copy full SHA for cd02770
1 file changed
number-of-1-bits/OstenHun.cpp
@@ -0,0 +1,42 @@
1
+/*
2
+ 191. Number of 1 Bits
3
+
4
+ Given a positive integer n, write a function
5
+ that returns the number of set bits in its binary representation
6
+ (also known as the Hamming weight).
7
8
+ Example 1:
9
+ Input: n = 11
10
+ Output: 3
11
12
+ Explanation:
13
+ The input binary string 1011 has a total of three set bits.
14
15
+ Constraints:
16
+ 1 <= n <= 2^31 - 1
17
+*/
18
19
+// 비트 연산을 이용하여 풀기
20
+#include <iostream>
21
+using namespace std;
22
23
+class Solution {
24
+public:
25
+ int hammingweight(int n) {
26
+ unsigned int answer = 0;
27
+ while(n>0) {
28
+ if (n & 1)
29
+ answer++;
30
+ n = n >> 1;
31
+ }
32
+ return answer;
33
34
+};
35
36
+int main() {
37
+ int n;
38
+ cin >> n;
39
+ Solution s;
40
41
+ cout << s.hammingweight(n);
42
+}
0 commit comments