leetcode 50. Pow(x, n)

256 阅读1分钟

题目链接

思路

在递归的过程中,每次计算n/2次幂,减少乘法计算的次数。注意0次幂以及负数次幂。

具体细节见代码(已提交通过)。

func myPow(x float64, n int) float64 {
        if n == 0 {
                return 1
        }
        var negative bool
        if n < 0 {
                 negative = true
                 n = -n
        }
        var res float64
        switch n {
                case 5:
                        res = x * x * x * x * x
                case 4:
                        res = x * x * x * x
                case 3:
                        res = x * x * x
                case 2:
                        res = x * x
                case 1:
                        res = x
                default:
                        if n&1 != 0 {
                                y := myPow(x, n/2)
                                res = y * y * x
                        } else {
                                y := myPow(x, n/2)
                                res = y * y
                        }
            }
        if negative {
                return 1/res
        }
        return res
}