[Leetcode] Pow (x, n)
Question:
Implement pow(x, n).
Analysis:
The question is very short, that is, to implement the power function of pow. Intuition tells me that the main requirement of this question is to reduce the time complexity of the program. If it is not clear, I submitted a while loop with the complexity of O (n) the error "Time Limit Exceed" is returned. The code is submitted for the first Time:
class Solution {public: double myPow(double x, int n) { double res = 1; while(n > 0) { res*=x; n--; } return res; }};
Then the binary power is used to optimize the code and reduce the Time complexity to O (logn). The Code below is still a "Time Limit Exceed" error.
class Solution {public: double myPow(double x, int n) { if(n==0) return 1; else { while((n&1)==0) { n>>=1; x*=x; } } double result=x; n>>=1; while(n!=0) { x*=x; if((n&1)!=0) result*=x; n>>=1; } return result; }};
It seems that the complexity must be reduced to O (1) to pass. I want to change my mind. Can I use something in the c ++ standard library and use the x ^ n = exp (log (x) * n) algorithm to reduce it to O (1 ), at the same time, if the value of the log function parameter is negative, it is successfully passed. The Code is as follows:
class Solution {public: double myPow(double x, int n) { if(x<0&&n%2==0) x = -x; if(x<0&&n%2!=0) return -exp(log(-x)*n); return exp(log(x)*n); }};