leetcide 50 Pow(x, n)

問題描述

Implement pow(x, n), which calculates x raised to the power n (xn).
題目要求咱們實現一個求x的n次冪的函數(pow函數),其中冪次數也能夠是複數。
其中n是Integer類型,範圍是 [−2^31, 2^31 − 1]。x的範圍是(-100,100)

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函數

想法

若是單純的暴力循環的話,會引發超時的問題。
咱們在這裏能夠用一種二分法的思想解決這個問題。
同時注意當n爲−2^31時,若是直接讓n=-n會溢出的問題。

解法

public double myPow(double x, int n) {
        if (n == 0) return 1;
        if (n < 0){
            x = 1/x;
            return (n %2 == 0) ? myPow(x*x, -(n/2)) : x*myPow(x*x, -(n/2));
        }
        return (n %2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
    }
相關文章
相關標籤/搜索