-
Notifications
You must be signed in to change notification settings - Fork 0
[LeetCode] 50. Pow(x, n) #102
Copy link
Copy link
Open
Description
题目描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
解题思路:使用递归,每次折半来进行运算。
C++解题:
class Solution {
public:
double myPow(double x, int n) {
if(n == 0) return 1;
double half = myPow(x,n/2);
if(n % 2 == 0) return half*half;
if(n > 0) return x*half*half;
return half*half/x;
}
};
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels