LeetCode: Pow(x, n)

早早投降了,看了这个强大的代码

 1 class Solution {

 2 public:

 3     double pow(double x, int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         bool negtive = n < 0;

 7         n = abs(n);

 8         double ret = 1.0;

 9         while (n > 0) {

10             ret = (n & 1) == 1? ret*x : ret;

11             x *= x;

12             n >>= 1;

13         }

14         return negtive? 1/ret : ret;

15     }

16 };

 C# 注意下Int32.MinValue问题就行

 1 public class Solution {

 2     public double MyPow(double x, int n) {

 3         bool neg = n < 0;

 4         bool minValue = false;

 5         if (n == Int32.MinValue) {

 6             n = Int32.MaxValue;

 7             minValue = true;

 8         }

 9         else n = Math.Abs(n);

10         double ans = 1.0;

11         double x1 = x;

12         while (n > 0) {

13             ans = (n & 1) == 1? ans * x1 : ans;

14             x1 *= x1;

15             n >>= 1;

16         }

17         if (minValue) ans *= x;

18         return neg? 1 / ans : ans;

19     }

20 }
View Code

 

你可能感兴趣的:(LeetCode)