-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpow_of_x_n.go
128 lines (99 loc) · 1.36 KB
/
pow_of_x_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
/*
func solve(x float64, n int64) float64 {
ans := 1.0
for n > 0 {
if n&1 == 1 {
ans *= x
}
x *= x
n >>= 1
}
return ans
}
func myPow(x float64, n int) float64 {
if x == 1 {
return 1
}
longN := int64(n)
var ans float64
if longN < 0 {
ans = 1 / solve(x, -longN)
} else {
ans = solve(x, longN)
}
return ans
}
------------------------------------------------------Solution----------
func solve(x float64, n int64) float64 {
if n == 0 {
return 1.0 // power of 0 is 1
}
temp := solve(x, n/2)
temp *= temp
if n%2 == 0 {
return temp
} else {
return temp * x
}
}
func myPow(x float64, n int) float64 {
if x == 1 {
return 1
}
longN := int64(n)
ans := solve(x, int64(longN))
if longN < 0 {
return 1 / ans
}
return ans
}
// Iterative BitWise
func myPow(x float64, n int) float64 {
if x == 1 {
return 1
}
if n == 0 {
return 1
}
if n < 0 {
x = 1 / x
n = -n
}
ans := 1.0
for n > 0 {
if n&1 == 1 {
ans *= x
}
x *= x
n >>= 1
}
return ans
}
*/
// Fastest Bitwise
func power(x float64, n int) float64 {
if n == 0 {
return 1
}
if n%2 == 0 {
return power(x*x, n/2)
}
return x * power(x, n-1)
}
func myPow(x float64, n int) float64 {
if n == 0 {
return 1
}
var l int
if n < 0 {
l = -n
} else {
l = n
}
ans := power(x, l)
if n < 0 {
return 1 / ans
}
return ans
}