-
Notifications
You must be signed in to change notification settings - Fork 2
/
powx-n.go
73 lines (69 loc) · 978 Bytes
/
powx-n.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package math
// https://leetcode-cn.com/problems/powx-n/
// Time: O(n)
func myPow(x float64, n int) float64 {
if n == 0 {
return 1
}
positive := true
if n < 0 {
n = -n
positive = false
}
var ret = 1.0
for i := 0; i < n; i++ {
ret *= x
}
if !positive {
ret = 1 / ret
}
return ret
}
// Time: O(logn)
// 2^11 = 2^8 * 2^2 * 2^1
func myPow2(x float64, n int) float64 {
if n == 0 {
return 1
}
positive := true
if n < 0 {
n = -n
positive = false
}
var ret, cal = 1.0, x
k := 1
for n != 0 {
k *= 2
if k <= n {
cal *= cal
} else {
n -= k / 2
k = 1
ret *= cal
cal = x
}
}
if !positive {
ret = 1.0 / ret
}
return ret
}
// A beautiful solution
// @see https://leetcode-cn.com/problems/powx-n/comments/10689
// Time: O(logn)
func myPow3(x float64, n int) float64 {
if n == 0 {
return 1
}
ret := 1.0
for i := n; i != 0; i /= 2 {
if i%2 != 0 {
ret *= x
}
x *= x
}
if n < 0 {
ret = 1 / ret
}
return ret
}