博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lintcode:Pow(x, n)
阅读量:6913 次
发布时间:2019-06-27

本文共 1866 字,大约阅读时间需要 6 分钟。

Pow(x, n)

Implement pow(x, n).

解题

直接顺序求解,时间复杂度O(N)

public class Solution {    /**     * @param x the base number     * @param n the power number     * @return the result     */    public double myPow(double x, int n) {        // Write your code here        if(x == 0)            return 0;        if(n == 0)            return 1.0;        if( n<0)            return 1.0/(myPow(x,-n));        double res = x;        while(n>1){            res*=x;            n--;        }        return res;    }}
Java Code

 

class Solution:    # @param {double} x the base number    # @param {int} n the power number    # @return {double} the result    def myPow(self, x, n):        # Write your code here        return x**n

 递归方式

对n时候奇数还是偶数的时候进行讨论

public class Solution {    /**     * @param x the base number     * @param n the power number     * @return the result     */    public double myPow(double x, int n) {        // Write your code here        if(x == 0)            return 0;        if(n == 0)            return 1.0;        if( n<0)            return 1.0/(myPow(x,-n));        double res = myPow(x,n/2);                if(n%2==1){            res = res * res *x;        }else{            res = res * res;        }         return res;    }}

递归程序中间需要比较多的栈,容易发生内存溢出的情况

 改写成循环的形式,效果更好,参考于libsvm源码

public class Solution {    public double myPow(double x, int n) {        if(n==0)            return 1.0;        if(x==1)            return 1.0;        if(n<0){            if (n == Integer.MIN_VALUE)                return myPow(x, n+1)/x;            else                 return 1.0/myPow(x, -n);        }                            double tmp = x;        double ret = 1.0;        for(int time = n;time>0;time/=2){            if(time%2==1)                ret *= tmp;            tmp*=tmp;        }        return ret;    }}

上面程序对n是最小值得时候进行了处理,LeetCode测试样例有 2 ,Integer.MIN_VALUE ,上面单独处理,可以通过

转载地址:http://epicl.baihongyu.com/

你可能感兴趣的文章
分析一个C语言程序生成的汇编代码-《Linux内核分析》Week1作业
查看>>
JavaScript数组操作方法集合(2)
查看>>
android Android SDK Manager遇到的问题
查看>>
RadioButton与监听
查看>>
Android开发技术周报183学习记录
查看>>
移位运算符
查看>>
warning: rpmts_HdrFromFdno: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY
查看>>
lamp环境安装
查看>>
springboot shiro配置
查看>>
Function
查看>>
Tomcat意外宕机分析
查看>>
LeetCode——58 Java之最后一个单词的长度
查看>>
ZetCode PyQt4 tutorial basic painting
查看>>
WPF RichTextBox的Document属性的序列化与反序列化
查看>>
显示照片方法之一
查看>>
InfoPath读取List到重复表
查看>>
微信公众平台二 文本编辑器与表单工具
查看>>
常用的php函数库
查看>>
迭代器 生成器
查看>>
初始Winsock编程
查看>>