Leetcode 题目解析之 Power of Two & Pow(x, n)

2022-01-20 12:47:39 浏览数 (1)

Given an integer, write a function to determine if it is a power of two.

代码语言:javascript复制
    public boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        return (n & (n - 1)) == 0;
    }

Implement pow(x, n).

代码语言:javascript复制
    public double myPow(double x, int n) {
        if (n < 0) {
            return 1 / pow(x, -n);
        } else {
            return pow(x, n);
        }
    }
    private double pow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double v = pow(x, n / 2);
        if (n % 2 == 0) {
            return v * v;
        } else {
            return v * v * x;
        }
    }
}

0 人点赞