博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]Pow(x, n) @ Python
阅读量:7280 次
发布时间:2019-06-30

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

原题地址:https://oj.leetcode.com/problems/powx-n/

题意:Implement pow(xn).

解题思路:求幂函数的实现。使用递归,类似于二分的思路,解法来自Mark Allen Weiss的《数据结构与算法分析》。

正确代码:

class Solution:    # @param x, a float    # @param n, a integer    # @return a float    def pow(self, x, n):        if n == 0:            return 1.0        elif n < 0:            return 1 / self.pow(x, -n)        elif n % 2:            return self.pow(x*x,n/2)*x        else:            return self.pow(x*x,n/2)

 

代码:

这段代码似乎无法ac,因为没有处理指数为负数的情况。

class Solution:    # @param x, a float    # @param n, a integer    # @return a float    def pow(self, x, n):        if n == 0:            return 1        elif n == 1:            return x        elif n % 2:            return self.pow(x*x,n/2)*x        else:            return self.pow(x*x,n/2)

 

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

你可能感兴趣的文章
is null为判断条件
查看>>
突击一下C语言
查看>>
erlang判定闰年,并用eunit测试
查看>>
DatetimeUtil工具类--用于Date和字符串互转的工具类
查看>>
escape()、encodeURI()、encodeURIComponent()区别详解
查看>>
GitLab 7.13.x安装和配置<二>--Linux篇
查看>>
mybatis调用oracle存储过程
查看>>
shell练习五
查看>>
踩坑Apache HttpEntity
查看>>
Core Data的使用(二)
查看>>
MYSQL外键(Foreign Key)的使用
查看>>
导入开源库到基于Android Studio构建的项目中
查看>>
Maven 在eclispe中集成本地插件报错解决方案
查看>>
Ubuntu中必装的十个应用程序
查看>>
Object-c 单例模式中的 allocWithZone作用
查看>>
分享一个H5原生form表单的checkbox特效
查看>>
nodejs+npm+webpack+vue+ElementUI+vue-route
查看>>
JAVA编程插入Excel文件到Word数据区域
查看>>
Highcharts 3.0.8功能特性使用评测
查看>>
大型分布式网站架构实战项目分析
查看>>