Implement POW (X,N), Which calculatesXRaised to the powerN(Xn ).
Example 1:
Input: 2.00000, 10Output: 1024.00000
Example 2:
Input: 2.10000, 3Output: 9.26100
Example 3:
Input: 2.00000, -2Output: 0.25000Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 <X<100.0
- NIs a 32-bit signed integer, within the range [? 231,231? 1]
Maybe I think too much, because the negative number range of the int is more than the positive number range. to convert it to a positive integer, we need to consider another range.
class Solution {public: double myPow(double x, int n) { long long m=n; if(n<0){return pow(1/x, 0-m);} return pow(x, n); } double pow(double x, long long n) { if(0==n){return 1.0;} double a=0.0; a = pow(x, n/2); // cout<<a<<" "<<n<<endl; if(n%2){ return a*a*x; }else{ return a*a; } }};
I still feel bad. I found an article well written.
80021207
Leetcode 50 POW (x, y)