LeetCode --- Pow(x, n)

题目链接

题意:实现pos(x, n)功能, 其中x为double类型,n为int类型

附上代码:

 1 class Solution {
 2 public:
 3     double pow(double x, int n) {
 4         // handle several particular test cases
 5         if (n == 0) return 1;
 6         if (x == 1.0) return x;
 7         if (x == -1.0) return n % 2 == 1 ? -1 : 1;
 8         // "n" is positive or negative ?
 9         bool flag = n > 0 ? true : false;
10         n = abs(n);
11         // holds the answer
12         double ans = 1.0;
13         while (n) {
14             if (n % 2) ans *= x;
15             x *= x;
16             n /= 2;
17         }           
18         if (flag) return ans; 
19         else return 1.0 / ans;
20     }
21 };
原文地址:https://www.cnblogs.com/Stomach-ache/p/3776713.html