Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 21bf14e

Browse files
feat: add swift implementation to lcof2 problem: No.072 (doocs#3305)
1 parent 0707720 commit 21bf14e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

‎lcof2/剑指 Offer II 072. 求平方根/README.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,29 @@ public class Solution {
160160
}
161161
```
162162

163+
#### Swift
164+
165+
```swift
166+
class Solution {
167+
func mySqrt(_ x: Int) -> Int {
168+
if x == 0 {
169+
return 0
170+
}
171+
var left = 0
172+
var right = x
173+
while left < right {
174+
let mid = (left + right + 1) / 2
175+
if mid <= x / mid {
176+
left = mid
177+
} else {
178+
right = mid - 1
179+
}
180+
}
181+
return left
182+
}
183+
}
184+
```
185+
163186
<!-- tabs:end -->
164187

165188
<!-- solution:end -->
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func mySqrt(_ x: Int) -> Int {
3+
if x == 0 {
4+
return 0
5+
}
6+
var left = 0
7+
var right = x
8+
while left < right {
9+
let mid = (left + right + 1) / 2
10+
if mid <= x / mid {
11+
left = mid
12+
} else {
13+
right = mid - 1
14+
}
15+
}
16+
return left
17+
}
18+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /