Skip to content

Commit d55fd17

Browse files
klever34yanglbme
andauthored
feat: add swift implementation to lcof2 problem: No.004 (#2974)
* Swift implementation for LCOF2 004 * Update README.md * Update Solution.swift --------- Co-authored-by: Libin YANG <contact@yanglibin.info>
1 parent e07c6d0 commit d55fd17

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lcof2/剑指 Offer II 004. 只出现一次的数字/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,25 @@ function singleNumber(nums: number[]): number {
150150
}
151151
```
152152

153+
#### Swift
154+
155+
```swift
156+
class Solution {
157+
func singleNumber(_ nums: [Int]) -> Int {
158+
var ans: Int32 = 0
159+
for i in 0..<32 {
160+
var cnt = 0
161+
for num in nums {
162+
cnt += (num >> i) & 1
163+
}
164+
cnt %= 3
165+
ans |= Int32(cnt) << i
166+
}
167+
return Int(ans)
168+
}
169+
}
170+
```
171+
153172
<!-- tabs:end -->
154173

155174
<!-- solution:end -->
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
func singleNumber(_ nums: [Int]) -> Int {
3+
var ans: Int32 = 0
4+
for i in 0..<32 {
5+
var cnt = 0
6+
for num in nums {
7+
cnt += (num >> i) & 1
8+
}
9+
cnt %= 3
10+
ans |= Int32(cnt) << i
11+
}
12+
return Int(ans)
13+
}
14+
}

0 commit comments

Comments
 (0)