剑指 offer acwing 27 数值的整数次方 (快速幂)

题面

在这里插入图片描述

题解

坑点 1. 本题中 可能有负数 ,用快速幂需要转化成正数,最后再取倒数
坑点 2. 当n等于负无穷时,取相反数会超出int范围。要用long long

代码

class Solution {
    
    
public:
    double Power(double x, int n) {
    
    
    typedef long long LL;
    bool is_minus = n < 0;
    double res = 1;
    LL k = abs(LL(n));
    while (k) {
    
    
        if (k & 1) res = res * x;
        x = x * x;
        k >>= 1;
    }
    if (is_minus) res = 1 / res;
    return res;
}

};

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114922988