首页 > 代码库 > 050. Pow(x, n)

050. Pow(x, n)

 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 };

 

050. Pow(x, n)