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);
    }
相关文章
相关标签/搜索