title = “2020-ARTS-打卡第十五天” lastmod = 2026-01-26T15:43:06+08:00 tags = [“arts”, “java”, “leetcode”] categories = [“arts”] draft = false author = “tomyli” +++

Algorithm

题目

题目描述

求一个数的N次幂

题目解答

public class MyPow {

    public double doPow(double x, int n) {

        if(x == 0) {
            return 0;
        }

        if(x == 1 || n == 0) {
            return 1;
        }

        if(n == 1) {
            return x;
        }

        long b = n;
        if(b < 0) {
            x = 1 / x;
            b = -b;
        }

        double res = 1.0;
        while(b > 0) {
            if((b & 1) == 1) {
                res *= x;
            }

            x *= x;
            b >>= 1;
        }
        return res;

    }
}

Review

Tip

Share