LeetCode代码分析——50. Pow(x, n)(细节,i

2018-06-19  本文已影响13人  JackpotDC

题目描述

Implement pow(x, n), which calculates x raised to the power n (xn).
实现x的n次方操作。

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

思路分析

这个题很简单,最简单的方法是遍历,result*=x;

代码实现

public class Solution {

    /**
     * 304 / 304 test cases passed.
     *  Status: Accepted
     *  Runtime: 22 ms
     * @param x
     * @param n
     * @return
     */
    public double myPow(double x, int n) {
        if (n < 0) {
            return 1 / x * myPow(1 / x, -(n + 1));
        }
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }

        double half = myPow(x, n >> 1);
        half *= half;

        if ((n & 1) == 1) {
            half *= x;
        }

        return half;
    }

}
上一篇下一篇

猜你喜欢

热点阅读