标签:
题目描述:
Implement pow(x, n).
解题思路:
注意n可能是INT_MIN。
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 unsigned int exp = (unsigned int)n; 5 if (n < 0) { 6 exp = (unsigned int)(-n); 7 return 1.0 / myPow_l(x, exp); 8 } 9 10 return myPow_l(x, exp); 11 } 12 13 double myPow_l(double x, unsigned int n) { 14 if (n == 0) { 15 return 1; 16 } 17 18 if (n == 1) { 19 return x; 20 } 21 22 double result = myPow(x, n >> 1); 23 result *= result; 24 if ((n & 1) != 0) { 25 result *= x; 26 } 27 28 return result; 29 } 30 };
标签:
原文地址:http://www.cnblogs.com/skycore/p/5386190.html