[leetcode] Pow(x, n)
来源:互联网 发布:一建考试分享 知乎 编辑:程序博客网 时间:2024/06/05 05:41
From : https://leetcode.com/problems/powx-n/
Implement pow(x, n).
递归求解,空间复杂度为O(logn),时间复杂度为O(logn)
class Solution {public: double myPow(double x, int n) { long long int num = n; if(x==0.0) return 0; if(x == 1) return 1; if(x == -1) return (!(num&1))-(num&1); if(num < 0) return myPowCore(1/x, -num); return myPowCore(x, num); } double myPowCore(double x, long long int n) { if(n == 0) return 1; if(n == 1) return x; return ((n&1)*x+(!(n&1)))*myPowCore(x*x, n>>1); }};
非递归方法,空间复杂度为O(1),时间复杂度为O(logn)
class Solution {public: double myPow(double x, int n) { long long m = n; if(x == 0) return 0;else if(m == 0 || x == 1) return 1;else if(m < 0) {m = -m;x = 1/x;}double ans = 1;while(m) {if(m&1) {ans *= x;}m = m>>1;x *= x;}return ans; }};
0 0
- LeetCode: Pow(x, n)
- LeetCode Pow(x,n)
- [Leetcode] Pow(x, n)
- LeetCode: Pow(x, n)
- Leetcode: Pow(x,n)
- [LeetCode] Pow(x, n)
- [Leetcode] Pow(x,n)
- 【leetcode】Pow(x, n)
- [LeetCode]Pow(x, n)
- [leetcode]Pow(x, n)
- LeetCode-Pow(x, n)
- LeetCode - Pow(x, n)
- LeetCode | Pow(x, n)
- Pow(x, n) -leetcode
- 【leetcode】Pow(x, n)
- 【Leetcode】Pow(x, n)
- LeetCode Pow(x, n)
- Leetcode: Pow(x, n)
- 开放远程连接mysql
- java笔记11 模板设计模式
- ETL(数据仓库技术)
- Node.js学习--基础知识(4)--模块与包
- Generate Parentheses
- [leetcode] Pow(x, n)
- Utorrent死机恢复种子下载
- ORA-01940: 无法删除当前连接的用户(解决办法)
- 一个指针变量占几个字节问题
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 为何5000点上才出现慢牛
- 九九乘法表的练习
- 查找子字符串----KMP算法深入剖析
- Gray Code