[leetcode 50. Pow(x, n)]week 11

来源:互联网 发布:黄金利多利空数据软件 编辑:程序博客网 时间:2024/06/05 02:27

一、题目

Implement pow(xn).

二、代码

class Solution {

public:

   double myPow(double x, int n) {

       if (n<0){

           double tmp=myPower(x,-n);

           return 1.0/tmp;

       }

       else

       return myPower(x,n);

    }

   double myPower(double x, int n) {

       if (n==0)

       return 1;

       double tmp=myPower(x,n/2);

       if (n%2==0)

       return tmp*tmp;

       else

       return tmp*tmp*x;

    }

};


三、思路

对n分情况进行,另开一个函数递归调用得到结果。

原创粉丝点击