LeetCode---50. Pow(x, n)(指数运算x的n次方)

来源:互联网 发布:gta5妹子捏脸数据 编辑:程序博客网 时间:2024/04/29 23:43

Implement pow(xn).

Subscribe to see which companies asked this question

//思路:主要考察越界,n为负数等问题

方法一:API

public class Solution {    public double myPow(double x, int n) {     //  double   Math.pow(double ,double)        if(x==0){return 0;}        if(n==1){return x;}                double result=Math.pow(x,n);        return result;    }}
方法二://考虑 n=负数边界

public class Solution {    public double pow(double x, int n) {        if (n == 0) {            return 1;        }        if (n == 1) {            return x;        }        boolean isNegative = false;        if (n < 0) {            isNegative = true;            n *= -1;        }        int k = n / 2;        int l = n - k * 2;        double t1 = pow(x, k);        double t2 = pow(x, l);        if (isNegative) {            return 1/(t1*t1*t2);        } else {            return t1*t1*t2;        }    }}





0 0
原创粉丝点击