当前位置:编程学习 > C/C++ >>

[leetcode]Pow(x, n)

class Solution {
public:
    double powPositive(double x, int n){
        if(n == 0) return 1;
        if(n == 1) return x;
        
        double tmp;
        if(n%2 == 0){
            tmp = powPositive(x, n/2);
            return tmp*tmp;
        }
        
        tmp = powPositive(x, n/2);
        
        return tmp*tmp*x;
    }
    
    double pow(double x, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n >= 0) return powPositive(x,n);
        return 1/powPositive(x,-n);
        
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,