[leetcode.com]算法题目 - Pow(x, n)

Implement pow(xn).

 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         if (0==n) return 1.0;
 7         if (1==n) return x;
 8         
 9         int k = abs(n);
10         int remainder = k % 2;
11         
12         double result = 1;
13         
14         result = pow(x, k/2);
15         result = result*result*(1==remainder?x:1);
16         
17         if (n>0)
18             return result;
19         else
20             return 1.0/result; 
21     }
22 };
我的答案

思路:使用递归,思路会比较清晰。注意讨论n小于0的情况。

posted on 2013-09-13 20:11  Horstxu  阅读(492)  评论(0编辑  收藏  举报

导航