其他分享
首页 > 其他分享> > 2021.10.11 - JZ16.数值的整数次方

2021.10.11 - JZ16.数值的整数次方

作者:互联网

文章目录

1. 题目

在这里插入图片描述

2. 思路

(1) 模拟法

(2) 快速幂

3. 代码

public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public double myPow(double x, int n) {
        if (x == 1 || n == 0) {
            return 1;
        }
        if (x == -1) {
            return (n & 1) == 0 ? 1 : -1;
        }
        long nl = n;
        if (n < 0) {
            x = 1 / x;
            nl = -nl;
        }
        double res = 1.0;
        while (nl > 0) {
            res = res * x;
            if (res == 0) {
                return 0;
            }
            nl--;
        }
        return res;
    }
}

class Solution1 {
    public double myPow(double x, int n) {
        if (x == 0) {
            return 0;
        }
        long nl = n;
        if (n < 0) {
            x = 1 / x;
            nl = -nl;
        }
        return myPow(x, nl);
    }

    private double myPow(double x, long n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        double pre = myPow(x, n >> 1);
        pre *= pre;
        if ((n & 1) == 1) {
            pre *= x;
        }
        return pre;
    }
}

标签:11,pre,nl,2021.10,myPow,double,次方,return,JZ16
来源: https://blog.csdn.net/qq_44021223/article/details/120701616