Skip to content

Commit c95430d

Browse files
authored
feat: add swift implementation to lcof problem: No.56.2 (doocs#2945)
1 parent 8ebdd67 commit c95430d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof/面试题56 - II. 数组中数字出现的次数 II/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,33 @@ public class Solution {
202202
}
203203
```
204204

205+
#### Swift
206+
207+
```swift
208+
class Solution {
209+
func singleNumber(_ nums: [Int]) -> Int {
210+
var bitCounts = [Int](repeating: 0, count: 32)
211+
212+
for num in nums {
213+
var x = num
214+
for i in 0..<32 {
215+
bitCounts[i] += x & 1
216+
x >>= 1
217+
}
218+
}
219+
220+
var result = 0
221+
for i in 0..<32 {
222+
if bitCounts[i] % 3 == 1 {
223+
result |= 1 << i
224+
}
225+
}
226+
227+
return result
228+
}
229+
}
230+
```
231+
205232
<!-- tabs:end -->
206233

207234
<!-- solution:end -->
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
func singleNumber(_ nums: [Int]) -> Int {
3+
var bitCounts = [Int](repeating: 0, count: 32)
4+
5+
for num in nums {
6+
var x = num
7+
for i in 0..<32 {
8+
bitCounts[i] += x & 1
9+
x >>= 1
10+
}
11+
}
12+
13+
var result = 0
14+
for i in 0..<32 {
15+
if bitCounts[i] % 3 == 1 {
16+
result |= 1 << i
17+
}
18+
}
19+
20+
return result
21+
}
22+
}

0 commit comments

Comments
 (0)