- Leetcode剑指offer第16题(快速幂)
class Solution {
public:
double myPow(double x, int n) {
if(x==0) return 0;
long b=n;
double res=1;
if(n<0){
x = 1/x;
b = -b;
}
while(b){
if(b&1){
res *=x;
b--;
}
x *=x;
b>>=1;
}
return res;
}
};
class Solution(object):
def myPow(self, x, n):
if x==0: return 0;
res =1
if n<0:
n=-n
x=1/x
while n:
if n&1:
res*=x
x*=x
n>>=1
return res
此图来自https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/
复习几个知识点:
1.转自知乎,二进制十进制相互转换
https://zhuanlan.zhihu.com/p/75291280
2.转自知乎,位运算符
https://zhuanlan.zhihu.com/p/92620039
简单举例:
int a
a&1==1 如果成立表示a为奇数,即a二进制最后一位是1
a>>2相当于a/2,a<<2相当于a*2