leetcode数值的整数次方

1.暴力法

效率较低

2.快速幂

需要考虑几种情况:

x=0

n=0

n为负数

快速幂的基本代码如下:

int pow3(int a,int b)
{
    int ans = 1,base = a;
    while(b!=0)
    {
        if(b&1)
            ans *= base;
        base *= base;
        b>>=1;
    }
    return ans;
}

代码如下:

class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0) return 1;
        if(x==0)  return 0;
        long N = n;
        if (n < 0) {
            x = 1/x;
            N = -N;
        }
        double res = 1;
       //快速幂
        while (N > 0) {
            if ((N & 1) == 1) {
                res = res * x;
            }
            x *= x;
            N >>= 1;
        }
        return res;
    }
};
发布了219 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38196982/article/details/104969398