class Solution {
public:
double pow(double x, int n) {
if (n == 0) return 1; // if n == 0; return 1;
double half = pow(x, n/2);
if (n % 2 == 0) return half * half; //if n is even return power(x,n/2) * power(x,n/2)
else
if(n%2 ==1 || n%2 == -1)
{
if(n > 0) return half*half*x;
if(n<0)
{
return half*half*(1/x);
}
}
}
};
1 = when you met the int n we must consider this in the four case :
1.1 odd negative
1.2 odd positive
1.3 even positive
1.4 even positive
2 = wonderful recursive
calculate the half at first and then use this half to calculate the whole
but we must give the base value before the calculating of half or dead loop
3 = the negative odd % 2 = -1
the positive odd % 2 = 1
the negative and positive even %2 = 0