码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】50. Pow(x, n)

时间:2018-02-05 18:40:31      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:post   ack   style   get   target   int   测试   package   new   

Implement pow(x, n).

Example 1:

Input: 2.00000, 10  Output: 1024.00000

Example 2:

Input: 2.10000, 3   Output: 9.26100
package medium;

public class L50MyPow {
    // 调用Math.pow() 函数
    public double mypow(double x, int n) {
        double nn = n;
        return Math.pow(x, nn);
    }

    //本题就x的n次方,如求2的4次方。可以4个2相乘,也可以先两个2相乘,之后两个4在相乘。
    public double myPow(double x, int n) {
        //防止n越界2147483647,用long类型的N来代替n
        long N = n;
        double result = 1.0;
        // double类型的x 判断x是否为0
        if ((x - 0.0 < -0.000000000001) && n < 0) {
            return 0.0;
        }
        //指数小于零,求得的数是用负指数相反数求得的值的倒数。
        if (N < 0) {
            N = -N;
            x = 1 / x;
        }
        double current_product = x;
        for (long i = N; i > 0; i /= 2) {
            if ((i % 2) == 1) {
                result = result * current_product;
            }
            current_product = current_product * current_product;
        }
        return result;
    }

    public static void main(String[] args) {
        L50MyPow cc = new L50MyPow();
        //测试负数的整数次方。  4.0
        System.out.println(cc.myPow(-2, 2));
        System.out.println("!!!!!!!!!!!!!!!!!!!");
        //小数的负数次方   2.543114507074558E-5
        double re = cc.myPow(34.00515, -3);
        System.out.println(re);
        //小数的大正整数次方次方 0.0
        System.out.println(cc.myPow(0.00001, 2147483647));
    }
}

 

【Leetcode】50. Pow(x, n)

标签:post   ack   style   get   target   int   测试   package   new   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8418420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!