Pow (x, N)
Implement POW (x, N).
Idea: The topic is not difficult, but need to consider the situation is more.
The specific code is as follows:
public class Solution {public double Mypow (double x, int n) { Boolean isMin0 = true;//result minus if (x > 0 | | (n&1) = = 0) {//x>0 or n is even isMin0 = false;//is positive } x = x < 0?-x:x;//set x uniformly as positive double d = 1.0; if (n > 0) {//n in three cases while (n > 0) { d = d*x; n--; if ((Math.Abs (d-1.0) < 1e-15)) { d = 1.0;//default equals 1 break ; } else if ((Math.Abs (d) < 1e-15)) { d = 0;//default equals 0 break;}} } else if (n = = 0) { return 1; } else{ while (n < 0) { d = d/x; n++; if ((Math.Abs (d-1.0) < 1e-15)) { d = 1; break; } else if ((Math.Abs (d) < 1e-15)) { if (isMin0) {///divisor equals 0, will be equal to plus or minus infinity return double.min_value; } else{ return Double.max_value;}}} return ismin0?-d:d;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 50.Pow (x, N) (n-th-square of X) thinking and method of solving problems