File tree 2 files changed +47
-0
lines changed
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -237,6 +237,32 @@ public class Solution {
237
237
}
238
238
```
239
239
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
+
240
266
<!-- tabs: end -->
241
267
242
268
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments