50. Pow(x, n)
作者:互联网
50. Pow(x, n)
Medium
Implement pow(x, n), which calculates x raised to the power n (xn).
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:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
二分查找的变形题,直接暴力运算会超时. 可能会想到用dp数组来加速运算, 或者是递归.
注意负数的处理, 只要多加一个1 / x 即可. 而且只需要在最外层处理这个, 递归的时候只传绝对值
class Solution { public: double myPow(double x, int n) { if(0==n)return 1; double d=myPow(x,abs(n/2)); //abs是为了配合处理负数,如果不加abs,计算结果会乱 d= n%2? d*d*x:d*d; return n<0? 1/d:d; } };
标签:myPow,Pow,50,double,abs,Input,Output,Example 来源: https://www.cnblogs.com/lychnis/p/11749278.html