eg:2^10=1024,10=1010(二进制) 有1的位置对应2^8*2^2=2^10=1024
每次1010右移一位,看最后一位是不是1
每次右移一位,1111->2^8,2^4,2^2,2^1:幂次:1,2,4,8->2^0,2^1*2^1=2^2,2^2*2^2=2^4,2^4*2^4=2^8,
b=1010, x =2*2=4=2^2, 给101用
b=101, x =4*4=16=2^4, 给10用
b=10, x =16*16=2^8, 给1用
c++
classSolution{public:doublemyPow(double x,int n){if(x ==0)return0;long b = n;double res =1.0;if(b <0){
x =1/ x;
b =-b;}while(b >0){if((b &1)==1){
res *= x;}
x *= x;
b >>=1;}return res;}};
python
classSolution:defmyPow(self, x:float, n:int)->float:if x ==0:return0
res =1
b = n
if b<0:
b =-b
x =1/x
while b>0:if b &1==1:# 判断最后一位是不是1
res *= x
x *= x
b >>=1# b=b右移一位return res