Skip to content

Latest commit

 

History

History
55 lines (55 loc) · 1.35 KB

50.md

File metadata and controls

55 lines (55 loc) · 1.35 KB

#50. Pow(x, n) 题目链接

public class Solution {
    public double myPow(double x, int n) {
        double result = 1.0d;
        if (n == 0) {
            return result;
        }
        if (x == 1.0d) {
            return 1.0d;
        } else if (x == -1.0d) {
            return n % 2 == 0 ? 1.0d : -1.0d;
        }
        if (n > 0) {
            for (int i = 0; i < n; i++) {
                result *= x;
                if (result == 0.0d) {
                    return 0;
                }
            }
        } else {
            // 下面两行代码为了防溢出
            result *= (1 / x);
            n = -(n + 1);
            for (int i = 0; i < n; i++) {
                result *= (1 / x);
                if (result == 0.0d) {
                    return 0;
                }
            }
        }
        return result;
    }
}

利用递归的一个简洁的方式,时间复杂度为O(lgn),空间复杂度同样为O(lgn)

public class Solution {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double h = myPow(x, n / 2);
        if (n % 2 != 0) {
            if (n > 0) {
                return x * h * h;
            } else {
                return 1 / x * h * h;
            }
        }
        return h * h;
    }
}