首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

leetcode:Pow(x, n) (计算x的n次方) 【口试算法题】

2013-10-19 
leetcode:Pow(x, n) (计算x的n次方) 【面试算法题】题目:Implement pow(x, n).题意计算x的n次方,考虑复杂度

leetcode:Pow(x, n) (计算x的n次方) 【面试算法题】

题目:Implement pow(x, n).

题意计算x的n次方,考虑复杂度和n的取值。


n有可能是正数或者负数,分开计算。

用递归的做法讲复杂度降到O(logn)。

class Solution {public:    double pow(double x, int n) {        if(n==0)return 1;        if(n==1)return x;        double temp=pow(x,abs(n/2));        if(n>0)        {            if(n&1)return temp*temp*x;            else return temp*temp;        }        else         {            if(n&1)return 1.0/(temp*temp*x);            else return 1.0/(temp*temp);        }    }};// blog.csdn.net/havenoidea

题解目录

热点排行