当前位置:网站首页>剑指 Offer 16. 数值的整数次方
剑指 Offer 16. 数值的整数次方
2022-08-03 21:00:00 【愈努力俞幸运】
剑指 Offer 16. 数值的整数次方
https://leetcode.cn/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
与运算与位运算可以参考
暴力求解会超时
class Solution:
def myPow(self, x, n):
res=1
if n>=0:
for i in range(n):
res=res*x
return res
else:
for i in range(-1*n):
res=res*x
return 1/res 
怎么就算X的次幂,每次循环令x=x*x即可
class Solution:
def myPow(self, x, n):
res=1
if n>=0:
while n:
if n&1:#判断n的二进制最后一位是否为1
res=res*x
x*=x
else: x*=x
n=n>>1
else:
n=-n
x=1/x
while n:
if n&1:#判断n的二进制最后一位是否为1,等同于n%2
res=res*x
x*=x
else: x*=x
n>>=1#等同于n//2
return res
a=Solution()
print(a.myPow(2,10))
print(a.myPow(2,-2))
边栏推荐
- Orcad Capture Cadence 新建原理图多部分smybol和Homogeneous、Heterogeneous类型介绍教程
- 通关剑指 Offer——剑指 Offer II 009. 乘积小于 K 的子数组
- svg+js订单确认按钮动画js特效
- Leetcode 16. Numerical integral power (power + fast recursive/iteration)
- 从开发到软件测试:除了扎实的测试基础,还有哪些必须掌握 ?
- 力扣59-螺旋矩阵 II——边界判断
- How can a cloud server safely use local AD/LDAP?
- 系统运维系列 之CSV文件读取时内容中包含逗号的处理方法
- idea2021.1.3版本如何启动多个客户端程序
- Five Steps to Detect and Control Shadow IT
猜你喜欢
随机推荐
leetcode 剑指 Offer 58 - II. 左旋转字符串
if _name_ == “__main__“:NameError: name ‘_name_‘ is not defined
LeetCode_位数统计_中等_400.第 N 位数字
leetcode 268. 丢失的数字(异或!!)
反射机制
敏捷交付的工程效能治理
直播源码开发,各种常见的广告形式
Leetcode 125. Verify palindrome string
火了十几年的零信任,为啥还不能落地
2022年强网杯rcefile wp
AWTK开发编译环境踩坑记录1(编译提示powershell.exe出错)
《QDebug 2022年7月》
ES6 introduction and let, var, const
力扣59-螺旋矩阵 II——边界判断
PyCharm函数自动添加注释无参数问题
XSS练习---一次循环和两次循环问题
DDD 中的几个困难问题
leetcode 16. 数值的整数次方(快速幂+递归/迭代)
XSS线上靶场---haozi
CLIP论文解读









