leetcode 50. Pow(x, n)
来源:互联网 发布:三菱plc控制软件 编辑:程序博客网 时间:2024/06/01 10:11
将指数用以2为底的幂代表,如14=8+4+2=1110,则x^14 = x^(8 + 4 + 2) = x ^ 8 * x ^ 4 * x ^ 2,使每一轮迭代的底数翻倍,检查指数在当前迭代的指示值是否为1,为1的话说明结果有当前这个底数的因子,由于指数的位数就是log(N)。所以时间的复杂度就是O(log(N))。这里也要注意精度溢出的问题。
class Solution {public: double myPow(double x, int n) { x = n < 0 ? 1 / x : x; long ln = labs(long(n)); double result = 1; while (ln) { result *= ln & 1 ? x : 1; x *= x; ln >>= 1; } return result; }};
递归版本更容易理解:
double pow(double x, int n) { if (n==0) return 1; double t = pow(x,n/2); if (n%2) { return n<0 ? 1/x*t*t : x*t*t; } else { return t*t; } }
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)
- 50. Pow(x, n) LeetCode
- [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)
- LeetCode - 50. Pow(x, n)
- [LeetCode] 50. Pow(x, n)
- LeetCode 50. Pow(x, n)
- 解决apache启动错误"httpd:Could not reliably determine..."
- C语言实现顺序表
- R-CNN、FastR-CNN、Faster R-CNN论文笔记
- 后盾网Laravel 5.2开发实战视频
- Codeforces problem 750E New Year and Old Subsequence
- leetcode 50. Pow(x, n)
- XCode打开工程无响应问题解决方案
- Ubuntu下安装JAVA(jdk8)
- macOS
- maven打包注意事项
- API接口的类型作用
- 关于list删除的问题
- macbook小技巧
- sql优化机制