Skip to content

Commit 00412c8

Browse files
author
Openset
committed
Add: powx_n
1 parent c88c1fc commit 00412c8

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

problems/powx-n/powx_n.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,16 @@
11
package powx_n
2+
3+
func myPow(x float64, n int) float64 {
4+
res := 1.0
5+
if n < 0 {
6+
n = -n
7+
x = 1 / x
8+
}
9+
for ; n > 0; n >>= 1 {
10+
if n&1 == 1 {
11+
res *= x
12+
}
13+
x *= x
14+
}
15+
return res
16+
}

problems/powx-n/powx_n_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,40 @@
11
package powx_n
2+
3+
import (
4+
"math"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
x float64
10+
n int
11+
expected float64
12+
}
13+
14+
func TestMyPow(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
x: 2.00000,
18+
n: 10,
19+
expected: 1024.00000,
20+
},
21+
{
22+
x: 2.10000,
23+
n: 3,
24+
expected: 9.26100,
25+
},
26+
{
27+
x: 2.00000,
28+
n: -2,
29+
expected: 0.25000,
30+
},
31+
}
32+
33+
for _, tc := range tests {
34+
output := myPow(tc.x, tc.n)
35+
output = math.Trunc(output*1e5) / 1e5
36+
if output != tc.expected {
37+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.x, tc.n, output, tc.expected)
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)