Leetcode: Pow (x, n)
I. Question
The question is very clear, that is, to implement the pow () function.
Ii. Analysis
After seeing the question, I first thought of computing one by one, and thought that it would time out. This reduces the number of operations. There is no difficult idea.
Although the idea is binary, there are different implementations. The following three types are used:
While implementation:
class Solution {public: double pow(double x, int n) { if(n == 0) return 1.0; if(n == 1) return x; int nflag = abs(n); int nflag2 = nflag; double xflag = abs(x); double xflag2 = xflag; int s = 1; while(nflag / 2 > 0){ xflag2 = xflag2 * xflag2; nflag = nflag / 2; s = s * 2; } xflag2 = xflag2 * pow(xflag, nflag2 - s); if(x < 0 && n % 2 == 1) xflag2 = -xflag2; if(n < 0) xflag2 = 1 / xflag2; return xflag2; }};
Recursive Implementation 1:
class Solution {public: double pow_help(double x, int n) { if(n == 0) return 1; double v = pow_help(x,n/2); if(n % 2 == 0) return v * v; else return v * v * x; }public: double pow(double x, int n) { if(n < 0) return 1 / pow_help(x,-n); else return pow_help(x,n); }};
Recursive Implementation 2:
class Solution {public: double pow(double x, int n) { if(n == 0) return 1.0; double res = pow(x,n/2); if(n % 2 != 0){ if(n > 0) return (res * res * x); else return (res / x * res); } return (res * res); }};