TypechoJoeTheme

IT技术分享

统计

[LeetCode 50] Pow(x, n) [Java] [Beats : 99.47%]

2017-08-06
/
0 评论
/
577 阅读
/
正在检测是否收录...
08/06

1. Description

Implement pow(x, n).

2. Runtime Distribution

3. Submission Details

4. Example

2^-2147483648 = 0.0

5. Code

public double myPow(double x, int n) {
    if (n == 0) {
        return 1;
    }
    double tmp = x, result = 1.0;

    long y = n;

    for (y = y < 0 ? -y : y; y != 0; y = y >> 1) {
        if ((y & 1) == 1) {
            result *= tmp;
        }
        tmp *= tmp;
    }

    return n < 0 ? 1 / result : result;
}

6.Test

public class LeetCode0050 {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double tmp = x, result = 1.0;

        long y = n;

        for (y = y < 0 ? -y : y; y != 0; y = y >> 1) {
            if ((y & 1) == 1) {
                result *= tmp;
            }
            tmp *= tmp;
        }

        return n < 0 ? 1 / result : result;
    }

    public static void main(String[] args) {
        LeetCode0050 leetcode = new LeetCode0050();
        System.out.println(leetcode.myPow(2, -2147483648));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/680/(转载时请注明本文出处及文章链接)