矩阵快速幂

50. Pow(x, n)

题目
实现 pow(x, n) ,即计算 x 的 n 次幂函数。

这里注意n的正反数越界问题。和leetcode 29. 两数相除这道题的注意点比较像,即当n取负数最小值时,其相反数会溢出。

class Solution {
     
    public double myPow(double x, int n) {
     
        double ans=1.0;
        double xx=x;
        int sign=1;
        long N=(long)n;
        if(N<0){
     
            N=-N;
            sign=-1;
        }
        while(N>0){
     
            if(N%2==1){
     
                ans*=xx;
            }
            xx=xx*xx;
            N/=2;
        }
        return sign==1?ans:(1.0/ans);
    }
}

你可能感兴趣的:(leetcode,#,数学)