Skip to content

Commit c954041

Browse files
authored
feat: add swift implementation to lcof problem: No.16 (doocs#2869)
1 parent d6c9b4f commit c954041

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

lcof/面试题16. 数值的整数次方/README.md

+26
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,32 @@ public class Solution {
237237
}
238238
```
239239

240+
#### Swift
241+
242+
```swift
243+
class Solution {
244+
func myPow(_ x: Double, _ n: Int) -> Double {
245+
return n >= 0 ? qpow(x, Int64(n)) : 1 / qpow(x, -Int64(n))
246+
}
247+
248+
private func qpow(_ a: Double, _ n: Int64) -> Double {
249+
var ans: Double = 1
250+
var base: Double = a
251+
var exponent: Int64 = n
252+
253+
while exponent > 0 {
254+
if (exponent & 1) == 1 {
255+
ans *= base
256+
}
257+
base *= base
258+
exponent >>= 1
259+
}
260+
261+
return ans
262+
}
263+
}
264+
```
265+
240266
<!-- tabs:end -->
241267

242268
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
func myPow(_ x: Double, _ n: Int) -> Double {
3+
return n >= 0 ? qpow(x, Int64(n)) : 1 / qpow(x, -Int64(n))
4+
}
5+
6+
private func qpow(_ a: Double, _ n: Int64) -> Double {
7+
var ans: Double = 1
8+
var base: Double = a
9+
var exponent: Int64 = n
10+
11+
while exponent > 0 {
12+
if (exponent & 1) == 1 {
13+
ans *= base
14+
}
15+
base *= base
16+
exponent >>= 1
17+
}
18+
19+
return ans
20+
}
21+
}

0 commit comments

Comments
 (0)