Title:
https://leetcode.com/problems/powx-n/
思路:二分。使用递归或者非递归。非递归有点难理解.pow(0,0)=1 递归的方法是将n为负数的用除法解决。有问题,没有考虑0的负数次幂会导致除数为0.对于非递归,可以这么理解,x是指数,不断增长,x , x^2, x^4,x^8
class Solution { public: double Pow(double x,int n){ if (n == 0) return 1.0; if (n == 1) return x; double a = Pow(x,n/2); if (n % 2 == 0) return a*a; else return a*a*x; } double myPow(double x,int n){ if (n < 0){ if (x == 0.0) return 0.0; else return 1.0/Pow(x,-n); } else{ return Pow(x,n); } } };
class Solution { public: double myPow(double x, int n) { if (0 == n) return 1.0; if (n < 0){ if (x == 0) return 0.0; else{ x = 1.0 / x; n = -1 * n; } } double result = 1.0; while (n > 0){ if (n & 1){ result *= x; } n /= 2; x *= x; } return result; } };