Leetcode|Pow(x,n)
来源:互联网 发布:propolinse漱口水知乎 编辑:程序博客网 时间:2024/05/16 23:53
Implement pow(x, n).
x是double类型,n是int类型;
边界条件:x==0和n==0
n为负数: 结尾取个倒数即可
效率问题:
解法1:一个一个乘,肯定超时。
解法2:用2的m次方和n比较。因为n可以表示成2的m次方的多项式相加的形式。
问题是:表示2的n次方(用移位表示),1<<30是(INT_MAX/2) ,1<<31 就是INT_MIN。
但是n==INT_MAX的情况怎么办呢。比如,输入0.00001, 2147483647 超时。
//无法处理INT_MAx的代码,多项式的运用。
double myPow(double x, int n) { if(x==0) return 0; if(n==0) return 1; bool isNeg=false; unsigned int pos=n; if(n<0) { isNeg=true; pos=-n;//有问题,INT_MIN } double res=1; int bit=0;//记录n和2的幂的关系 for(;(1<<bit)<=pos;bit++); bit--; double pow[bit+1]; for(int i=0;i<=bit;i++){//数组存不完全,最多到x的2^30次方 if(i==0) pow[i]=x; else pow[i]=pow[i-1]*pow[i-1]; } for(int i=bit;pos>0&&i>=0;i--){ if(pos>=(1<<i)){ res*=pow[i]; pos-=1<<i; } } return (!isNeg) ? res : (1/res); }
解法3:利用x=x*x 来快速减少n,以指数的速度减少。
利用无符号的整型保存n;
n为偶数的话,x=x*x,n>>1; n迟早都会是1,利用n为奇数时候res*=x;
n为奇数的话,res*=x;
例如n==15; 第一次检验n为奇数,res*=x;
n变为7,x变为2次方。
n为奇数,res*=x;(res为x的三次方)
n变为3,x为4次方。
n为奇数,res*=x;
。。。
res=1*x^1*x^2*x^4*x^8;
AC的代码。
double myPow(double x, int n) {
if(x==0) return 0;
if(n==0) return 1;
bool isNeg=false;
unsigned int pos=n;
double res=1;
if(n<0) {
isNeg=true;
pos=-n;
}
while(pos){
if(pos&1){
res*=x;
}
pos>>=1;
x*=x;
}
return (!isNeg) ? res : (1/res);
}
- 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)
- (4.1.23.0)Android Animation学习笔记及位移动画的P属性图示
- ZooKeeper 是什么?
- MySQL索引特性笔记
- 十个利用矩阵乘法解决的经典题目
- ZOJ 2770 Burn the Linked Camp 差分约束
- Leetcode|Pow(x,n)
- django中的ajax实现(GET)
- Java 理论与实践: 正确使用 Volatile 变量
- 键盘挡住文本,调整键盘高度简单办法
- MySQL的日志管理
- hdu 1151 Air Raid
- MySQL优化一之limit优化
- php 中大括号的规范
- POJ_1679_The Unique MST(次小生成树模板)