Skip to content

Commit d6c9b4f

Browse files
authored
feat: add swift implementation to lcof problem: No.15 (doocs#2868)
1 parent fc09c8c commit d6c9b4f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lcof/面试题15. 二进制中1的个数/README.md

+16
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,22 @@ var hammingWeight = function (n) {
147147
};
148148
```
149149

150+
#### Swift
151+
152+
```swift
153+
class Solution {
154+
func hammingWeight(_ n: Int) -> Int {
155+
var n = n
156+
var ans = 0
157+
while n != 0 {
158+
n &= (n - 1)
159+
ans += 1
160+
}
161+
return ans
162+
}
163+
}
164+
```
165+
150166
<!-- tabs:end -->
151167

152168
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution {
2+
func hammingWeight(_ n: Int) -> Int {
3+
var n = n
4+
var ans = 0
5+
while n != 0 {
6+
n &= (n - 1)
7+
ans += 1
8+
}
9+
return ans
10+
}
11+
}

0 commit comments

Comments
 (0)