-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathPowXN.swift
More file actions
36 lines (30 loc) · 719 Bytes
/
Copy pathPowXN.swift
File metadata and controls
36 lines (30 loc) · 719 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//
// PowXN.swift
// LeetCode
//
// Created by 黎赵太郎 on 26/11/2017.
// Copyright © 2017 lizhaotailang. All rights reserved.
//
// Implement pow(x, n).
//
// Accepted. See [PowXNTests](./LeetCodeTests/PowXNTests.swift) for test cases.
//
import Foundation
class PowXN {
func myPow(_ x: Double, _ n: Int) -> Double {
// return pow(x, Double(n))
if n == 0 {
return 1
}
if n == 1 {
return x
}
let result = myPow(x, n / 2)
if (n % 2) == 0 {
return result * result
} else if n > 0 {
return x * result * result
}
return (result * result) / x
}
}