当前位置:网站首页>剑指 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))
边栏推荐
- leetcode 461. 汉明距离
- idea2021配置svn报错Cannot run program “svn“ (in directory “xxx“):CreateProcess error=2,系统找不到指定的文件
- Why BI software can't handle correlation analysis
- PyCharm function automatically add comments without parameters
- leetcode 268. 丢失的数字(异或!!)
- 太香了! 阿里 Redis 速成笔记, 从头到尾全是精华!
- svg胶囊药样式切换按钮
- canvas螺旋动画js特效
- 收藏-即时通讯(IM)开源项目OpenIM-功能手册
- leetcode 136. Numbers that appear only once (XOR!!)
猜你喜欢

火了十几年的零信任,为啥还不能落地

leetcode 231. Powers of 2

Markdown syntax

Abs (), fabs () and LABS ()

Advantages and Disadvantages of Blind and Buried Via PCB Stacked Via Design

idea2021配置svn报错Cannot run program “svn“ (in directory “xxx“):CreateProcess error=2,系统找不到指定的文件

Engineering Effectiveness Governance for Agile Delivery

leetcode 231. 2 的幂

力扣707-设计链表——链表

Likou 59 - Spiral Matrix II - Boundary Judgment
随机推荐
Leetcode 125. Verify palindrome string
七夕快乐!
leetcode 268. Missing Numbers (XOR!!)
伪标签汇总
glusterfs build and use
直播平台怎么搭建,针对输入框的各种组件
直播源码开发,各种常见的广告形式
ES6--residual parameters
Leetcode 16. Numerical integral power (power + fast recursive/iteration)
ES6 deconstruction assignment - array object deconstruction and deconstruction
李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
盲埋孔PCB叠孔设计的利与弊
ES6 introduction and let, var, const
ES6 - Arrow Functions
系统运维系列 之CSV文件读取时内容中包含逗号的处理方法
双线性插值公式推导及Matlab实现
Leetcode 899. An orderly queue
leetcode 16.01. Swap numbers (swap the values of 2 numbers without using temporary variables)
chart.js多条曲线图插件
华为设备VRRP配置命令