leetcode golang实现 --------------- 实现一个数的整数次方 pow(x, n)

package main

/*
	实现一个数的整数次方
	pow(x, n)
*/

func pow(x float64, n int) float64 {
	if x == 0 {
		return 0
	}
	result := calPow(x, n)
	if n < 0 {
		result = 1 / result
	}
	return result
}

func calPow(x float64, n int) float64 {
	if n == 0 {
		return 1
	}
	if n == 1 {
		return x
	}

	// 向右移动一位
	result := calPow(x, n>>1)
	result *= result

	// 如果n是奇数
	if n&1 == 1 {
		result *= x
	}

	return result
}

猜你喜欢

转载自blog.csdn.net/yyhero1/article/details/79805914