leetcode刷题笔记(Golang)--50. Pow(x, n)

50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000
Example 2:

Input: 2.10000, 3
Output: 9.26100
Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

func myPow(x float64, n int) float64 {
	res := 0.0
	if n > 0 {
		res = recursion(x, n)
	} else {
		res = 1.0 / recursion(x, -n)
	}
	return res
}

func recursion(x float64, n int) float64 {
	if n == 0 {
		return 1
	}
	if n == 1 {
		return x
	}
	res := recursion(x*x, n/2)
	if n%2 == 1 {
		res *= x
	}
	return res
}
发布了65 篇原创文章 · 获赞 0 · 访问量 379

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104257534
今日推荐