-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path16.go
73 lines (67 loc) · 882 Bytes
/
16.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 main
/***
"题目:**数值的整数次方**
[数值的整数次方](https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof)
题目描述:
***/
/**
解法一
说明:
**/
func myPow(x float64, n int) float64 {
sum := 1.0
flag := false
if n < 0 {
n = -n
flag = true
}
for i := 0; i < n; i++ {
sum *= x
}
if flag {
sum = 1.0 / sum
}
return sum
}
// 迭代法
func myPow2(x float64, n int) float64 {
if n == 0 {
return 1
}
if n == 1 {
return x
}
if n < 0 {
n = -n
x = 1 / x
}
res := 1.0
for n >= 1 {
if n&1 == 1 {
res *= x
n--
} else {
x *= x
n = n >> 1
}
}
return res
}
// 递归法
func myPow3(x float64, n int) float64 {
if n == 0 {
return 1
}
if n == 1 {
return x
}
if n < 0 {
n = -n
x = 1 / x
}
temp := myPow(x, n/2)
if n%2 == 0 {
return temp * temp
}
return x * temp * temp
}