约 1 分钟64 字83 词
题目
原题页面:https://leetcode.com/problems/powx-n/
题目类型:Math, Binary Search
难度评价:Medium
类似题目:(M) Sqrt(x)
Implement pow(x, n).
分析
用n个x相乘显然不是应该出现在leetcode上的算法。这里是利用二分的算法,通过递归来加速计算。
例如,pow(x, 5) == (x * pow(x, 4)) == (x * pow(pow(x, 2), 2))。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution: def pow(self, x, n): if 0 == n: return 1 elif n < 0: return 1.0 / self.pow(x, -n) else: half = self.pow(x, n >> 1) if 0 == n % 2: return half * half else: return x * half * half
|
本文地址:https://xnerv.wang/leetcode-pow-x-n/