当前位置:网站首页>剑指 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))
边栏推荐
猜你喜欢
随机推荐
力扣59-螺旋矩阵 II——边界判断
leetcode 136. Numbers that appear only once (XOR!!)
业界新标杆!阿里开源自研高并发编程核心笔记(2022 最新版)
Li Mu hands-on learning deep learning V2-BERT fine-tuning and code implementation
通关剑指 Offer——剑指 Offer II 009. 乘积小于 K 的子数组
ES6 - Arrow Functions
双线性插值公式推导及Matlab实现
云服务器如何安全使用本地的AD/LDAP?
Power button 206 - reverse list - the list
leetcode 剑指 Offer 15. 二进制中1的个数
手动输入班级人数及成绩求总成绩和平均成绩?
error: C1083: 无法打开包括文件: “QString”: No such error: ‘QDir‘ file not found
svg+js订单确认按钮动画js特效
Why BI software can't handle correlation analysis
在树莓派上搭建属于自己的网页(3)
Zero trust, which has been popular for more than ten years, why can't it be implemented?
Likou 707 - Design Linked List - Linked List
15 years experience in software architect summary: in the field of ML, tread beginners, five hole
3种圆形按钮悬浮和点击事件
leetcode 231. 2 的幂









