题目:
Implement pow(x, n).
题解:
要用二分法递归。还要区分n的正负。
C++版:
class Solution { public: double myPow(double x, int n) { if(n == 0) return 1; if(n == 1) return x; double temp = myPow(x, abs(n / 2)); if(n > 0) { if(n & 1) return temp * temp * x; else return temp * temp; } else { if(n & 1) return 1 / (temp * temp * x); else return 1 / (temp * temp); } } };
public class Solution { public double myPow(double x, int n) { if(n == 0) return 1; if(n == 1) return x; double temp = myPow(x, Math.abs(n / 2)); if(n > 0) { if((n & 1) == 0) return temp * temp; else return temp * temp * x; } else { if((n & 1) == 0) return 1 / (temp * temp); else return 1 / (temp * temp * x); } } }
class Solution: # @param {float} x # @param {integer} n # @return {float} def myPow(self, x, n): if n == 0: return 1.0 if n == 1: return x if n > 1: return self.pow(x, n) else: return 1.0 / self.pow(x, -n) def pow(self, x, n): if n == 0: return 1.0 if n == 1: return x temp = self.pow(x, n / 2) if n % 2 == 0: return temp * temp else: return temp * temp * x