标签:
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 if (x == 0) return 0; 5 else { 6 if (n == 0 || x == 1) return 1; 7 else { 8 if (n > 0) { 9 double temp = myPow(x, n / 2); 10 if (n % 2 == 0) return temp * temp; 11 else return temp * temp * x; 12 } 13 else { 14 double temp = myPow(x, -(n / 2)); 15 if (n % 2 == 0) return 1.0 / (temp * temp); 16 else return 1.0 / (temp * temp * x); 17 } 18 } 19 } 20 } 21 };
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 if (x == 0) return 0; 5 else { 6 if (n == 0 || x == 1) return 1; 7 else { 8 if (n > 0) { 9 double temp = myPow(x, n / 2); 10 if (n % 2 == 0) return temp * temp; 11 else return temp * temp * x; 12 } 13 else { 14 double temp = myPow(x, -(n / 2)); // 这里一定要注意负值的最大可能越界 15 if (n % 2 == 0) return 1.0 / (temp * temp); 16 else return 1.0 / (temp * temp * x); 17 } 18 } 19 } 20 } 21 };
标签:
原文地址:http://www.cnblogs.com/shadowwalker9/p/5856936.html