[leetcode] 50.Pow(x, n)
来源:互联网 发布:安装mac终端改时间date 编辑:程序博客网 时间:2024/04/29 17:49
题目:Implement pow(x, n).
题意:实现pow函数。
思路:这题需要做的是思考全面。
- 在n=0时,直接返回1.
- 在n>0时,直接让n个x相乘,当然n个x相乘的不需要o(n)的复杂度,只需要o(lgn)的复杂度,比如求100个2相乘,那么我们只要求得50个2相乘的结果,二分法只要o(lgn)复杂度。如果超过double的精度需要返回标记异常,比如面试官会让用一个全局变量记住。
- 在n<0时,相当于求1/(pow(x,-n),此处要考虑当n是0x80000000即最大的负数时,int型的-n会超出异常,所以调用另一个函数myPow1(double x, long long n),让n变成long long类型。但是此刻要注意x是否为0,如果是0的话也需要标记异常。
- 为了提高速度,考虑x=0,x=1的特殊情况,直接可以返回0或者1.
以上,参见代码如下:
class Solution {public: double myPow(double x,int n){ return myPow1(x,n); } double myPow1(double x, long long n) { if(n == 0)return 1; else if(n == 1)return x; else if(n < 0 && x == 0)return 0; else if(x == 0)return 0; else if(x == 1)return 1; else if(n < 0)return 1/myPow1(x,-n); double temp = myPow1(x,n/2); double result = temp*temp; if(n%2 == 1)result *= x; return result; }};
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)
- CDC中的SelectObject
- 论战Yann LeCun:谁能解释极限学习机(ELM)牛X在哪里?
- 用js使得输入框input只能输入数字
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- [leetcode] 50.Pow(x, n)
- W25Q64简介(译)
- js实现页面跳转的几种方式
- 跳跃表
- 老师上课讲的,回去研
- 大素数判断和素因子分解(miller-rabin,Pollard_rho算法)
- linux命令之cp/scp 远程拷贝
- VM 虚拟机(客机系统)关机慢的解决
- IOS-IOS7小计