Leetcode-50: Pow(x,n)
2018-03-25 11:37
453 查看
参考了网上一个比较妙的解法。
要注意的地方有:
1) 当n为负数时,可以用1/x^(-n)。但要注意-MIN_VALUE转正时会溢出;
2) while循环内会记录factor=x^(2n)(不管n&0x1是否为1),这样就避免了冗余计算。
3) while循环内,当n&0x1=1时,就让result*=factor。比如说3^10=3^(2^1) * 3^(2^3)。#include <iostream>
using namespace std;
double myPow(double x, int n) {
if (n==0) return 1.0;
bool neg=false;
if (n<0) {n=-(n+1); neg=true;} //note MIN_MAX may overflow
double result=1.0;
double factor=x;
while(n) {
if (n & 0x1) result*=factor;
n=n>>1;
factor*=factor; //record x^(2n)
}
if (neg)
return 1.0/result/x;
else
return result;
}
int main()
{
cout<<myPow(2.0, 10)<<endl;
cout<<myPow(2.1, 3)<<endl;
return 0;
}
解法2:递归
下次补充
要注意的地方有:
1) 当n为负数时,可以用1/x^(-n)。但要注意-MIN_VALUE转正时会溢出;
2) while循环内会记录factor=x^(2n)(不管n&0x1是否为1),这样就避免了冗余计算。
3) while循环内,当n&0x1=1时,就让result*=factor。比如说3^10=3^(2^1) * 3^(2^3)。#include <iostream>
using namespace std;
double myPow(double x, int n) {
if (n==0) return 1.0;
bool neg=false;
if (n<0) {n=-(n+1); neg=true;} //note MIN_MAX may overflow
double result=1.0;
double factor=x;
while(n) {
if (n & 0x1) result*=factor;
n=n>>1;
factor*=factor; //record x^(2n)
}
if (neg)
return 1.0/result/x;
else
return result;
}
int main()
{
cout<<myPow(2.0, 10)<<endl;
cout<<myPow(2.1, 3)<<endl;
return 0;
}
解法2:递归
下次补充
相关文章推荐
- leetcode50_Pow(x, n)
- LeetCode 50 Pow(x, n)
- Leetcode(50):Pow(x, n)
- LeetCode 50 Pow(x, n)
- 【LeetCode】C# 50、Pow(x, n)
- LeetCode 50:Pow(x, n)
- LeetCode_50---Pow(x, n)
- LeetCode50_Pow(x,n)
- Leetcode50 Pow(x,n)
- LeetCode(50) Pow(x, n)
- [LeetCode-Algorithms-50] "Pow(x, n)" (2017.10.25-WEEK8)
- leetcode || 50、Pow(x, n)
- Leetcode 50 Pow(x, n)
- leetcode-50-Pow(x, n)
- LeetCode---(50)Pow(x, n)
- LeetCode - 50/69/367/633 - Pow(x, n)、Sqrt(x)
- leetcode-50 Pow(x, n) 剑指Offer题11 数值的整数次方
- [LeetCode]50 Pow(x, n)
- leetcode 50:Pow(x, n)
- 50. Pow(x, n) LeetCode