JZ12 数值的整数次方

数值的整数次方

https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&&tqId=11165&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2021年9月14日21:06:53
递归

public class Solution {
    public double Power(double base, int exponent) {
        if(exponent == 0) return 1;
        else if(exponent>0) return base * Power(base,exponent-1);
        else return 1/base*Power(base,exponent+1);
  }
}

快速幂
图片说明 k神

class Solution {
    public double myPow(double x, int n) {
        if(x == 0) return 0;
        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;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务