【LeetCode】50、pow(x,n)
来源:互联网 发布:数据库与数据仓库 编辑:程序博客网 时间:2024/06/02 02:29
1、http://blog.csdn.net/nerv3x3/article/details/3465663
二分法一步步分解,并使用递归的方法:
幂运算可以利用二分的方法来做。也就是x^n = x ^ (n /2) * x ^(n / 2) (n %2 == 0)或者x^n = x ^ (n /2) * x ^(n / 2) * x(n %2 == 1)。要注意的时候,当n < 0 的时候,x ^ n =1 / (x ^(-n))。
class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if(n<0): return 1.0/self.myPow(x,-n) if n==0: return 1.0 if n==1: return x tmp = self.myPow(x,n/2) if n%2==0: return tmp*tmp else: return tmp*tmp*x
如果没有使用tmp这个变量临时存储self.myPow(x,n/2),而是使用self.myPow(x,n/2)*self.myPow(x,n/2)的话,式子计算了两遍,增加了运算时间,容易造成超时(time limit exceed)。
注意调用函数要用self.func()。可以在一个类里面相互调用函数。
阅读全文
0 0
- leetcode 50 : Pow(x, n)
- LeetCode 50: Pow(x, n)
- [leetcode 50] Pow(x, n)
- [Leetcode] 50 - Pow(x, n)
- [LeetCode 50]Pow(x, n)
- leetcode 50 Pow(x, n)
- leetcode || 50、Pow(x, n)
- [leetcode] #50 Pow(x,n)
- LeetCode-50 Pow(x, n)
- Pow(x, n) - LeetCode 50
- Leetcode(50):Pow(x, n)
- LeetCode---(50)Pow(x, n)
- Leetcode #50 Pow(x, n)
- LeetCode(50) Pow(x, n)
- leetcode 50: Pow(x, n)
- Leetcode#50||Pow (x, n)
- [Leetcode]#50 Pow(x, n)
- leetcode 50:Pow(x, n)
- String类笔记
- Linux常用目录的作用
- C++设计模式——单例模式
- iOS开发代码规范
- vue中运行程序会出现插值的形式,{{msg}}
- 【LeetCode】50、pow(x,n)
- linux grep 正则表达式
- android studio 2.3 编译动态库
- 数据库SQL优化大总结
- HashMap源代码分析(JDK1.8)
- 亚马逊新规出台,外贸建站时代呼之欲出!
- Dijkstra算法
- 老男孩python14期,day1
- 星型模型和雪花型模型比较