Implement POW (double x, int n). –leetcode
Custom implementation POW function.
Note the point:
(1) The value of double type, cannot use = = to judge whether equal, should use a certain error value to judge;
(2) Handling of special cases:
1) x is 0 and n is 0
2) x is not 0, N is 0
3) x is not 0, N is a negative case. (You can convert negative numbers to positive numbers and then the inverse of the results.) Note: The minimum value of a negative number, converted to positive, will cross the border. The solution is to add 1 to the negative, then to positive, then multiply 1/x to ensure the result.
If the process of iterative iteration is solved directly, the time complexity is too high and it is difficult to compile. Observation can know:
When n > 0 o'clock:
According to the iteration formula-there is code:
Public:Double Power(Double Base,intExponent) {The //base index is 0, equal (base,0) is to determine whether the bases and 0 are equal (special case processing, here when the radix index is 0, the value is 1) if(Equal (Base,0) && exponent = =0)return 1.0;//index is 0 if(Exponent = =0)return 1.0;//exponent is plural if(Exponent <0){//exponent is negative, exponent plus 1, then convert to positive return 1/Base* Powerwithexponent (1/Base,-(exponent+1)); }//exponent is positive returnPowerwithexponent (Base, exponent); }//recursive solution to think: //a^x = (1) a^ (X/2) * a^ (X/2) x is even //(2) a^ ((x-1)/2) * a^ ((x-1)/2) * A x is odd DoublePowerwithexponent (Double Base,intExponent) {//index is 0, return 1 if(Exponent = =0)return 1;//index is 1, back to base if(Exponent = =1)return Base;Doubleresult = Powerwithexponent (Base, exponent >>1);//exponent >> 1 bit shift operation, equivalent to dividing by 2, but better performanceResult *= result;if(Exponent &0x1){//exponent & 0x1 is equivalent to the% operation, better performance. Exponent & 0x1 = = 1 means oddResult *=Base; }returnResult }//Determine if two double is equal and cannot be solved with = = BOOLEqual (DoubleADoubleb) {if(A-B >-0.0000001) && (A-B) <0.0000001)return true;Else return false; } };
Pow (x, N)--Leetcode