Skip to content

Commit 0d8ce24

Browse files
authored
feat: add swift implementation to lcci problem: No.05.03 (doocs#2667)
1 parent 5c3b128 commit 0d8ce24

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

lcci/05.03.Reverse Bits/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,27 @@ func reverseBits(num int) (ans int) {
9191
}
9292
```
9393

94+
```swift
95+
class Solution {
96+
func reverseBits(_ num: Int) -> Int {
97+
var ans = 0
98+
var countZeros = 0
99+
var j = 0
100+
101+
for i in 0..<32 {
102+
countZeros += (num >> i & 1 ^ 1)
103+
while countZeros > 1 {
104+
countZeros -= (num >> j & 1 ^ 1)
105+
j += 1
106+
}
107+
ans = max(ans, i - j + 1)
108+
}
109+
110+
return ans
111+
}
112+
}
113+
```
114+
94115
<!-- tabs:end -->
95116

96117
<!-- end -->

lcci/05.03.Reverse Bits/README_EN.md

+21
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,27 @@ func reverseBits(num int) (ans int) {
9797
}
9898
```
9999

100+
```swift
101+
class Solution {
102+
func reverseBits(_ num: Int) -> Int {
103+
var ans = 0
104+
var countZeros = 0
105+
var j = 0
106+
107+
for i in 0..<32 {
108+
countZeros += (num >> i & 1 ^ 1)
109+
while countZeros > 1 {
110+
countZeros -= (num >> j & 1 ^ 1)
111+
j += 1
112+
}
113+
ans = max(ans, i - j + 1)
114+
}
115+
116+
return ans
117+
}
118+
}
119+
```
120+
100121
<!-- tabs:end -->
101122

102123
<!-- end -->
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func reverseBits(_ num: Int) -> Int {
3+
var ans = 0
4+
var countZeros = 0
5+
var j = 0
6+
7+
for i in 0..<32 {
8+
countZeros += (num >> i & 1 ^ 1)
9+
while countZeros > 1 {
10+
countZeros -= (num >> j & 1 ^ 1)
11+
j += 1
12+
}
13+
ans = max(ans, i - j + 1)
14+
}
15+
16+
return ans
17+
}
18+
}

0 commit comments

Comments
 (0)