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 b689915 commit 8448f5bCopy full SHA for 8448f5b
number-of-1-bits/JustHm.swift
@@ -0,0 +1,21 @@
1
+// time: O(n)
2
+class Solution {
3
+ func hammingWeight(_ n: Int) -> Int {
4
+ return String(n, radix: 2).filter{$0 == "1"}.count
5
+ }
6
+}
7
+// time: O(1), space: O(1)
8
+class AnotherSolution {
9
10
+ var count = 0
11
+ var num = n
12
+ // 최대 32비트이기 때문에 반복을 32번 돌며 비트를 순회함
13
+ for _ in 0..<32 {
14
+ if num & 1 == 1 { // 가장 오른쪽 비트만 가져와 1인지 확인함
15
+ count += 1 // 비트가 1이면 count 증가
16
17
+ num >>= 1 // 오른쪽으로 1비트 이동
18
19
+ return count
20
21
0 commit comments