当前位置:网站首页>剑指 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 125. 验证回文串
- Zero trust, which has been popular for more than ten years, why can't it be implemented?
- 好朋友离职了,一周面试了20多场,我直呼内行
- Edge box + time series database, technology selection behind Midea's digital platform iBuilding
- 力扣203-移除链表元素——链表
- leetcode 072. Finding Square Roots
- leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
- 业界新标杆!阿里开源自研高并发编程核心笔记(2022 最新版)
- leetcode refers to Offer 58 - II. Left Rotate String
- 《富爸爸,穷爸爸》思维导图和学习笔记
猜你喜欢
随机推荐
基于data.table的tidyverse?
Leetcode 16. Numerical integral power (power + fast recursive/iteration)
数据库定时备份winserver2012篇
leetcode refers to Offer 58 - II. Left Rotate String
解决This application failed to start because no Qt platform plugin could be initialized的办法
3种圆形按钮悬浮和点击事件
字节跳动软件测试岗,前两面过了,第三面HR天坑,结局透心凉...
2022-8-3 第七组 潘堂智 锁、多线程
win10安装及配置Gradle
Five Steps to Detect and Control Shadow IT
独立站卖家在哪些平台做社交媒体营销效果最好?
跨端开发技术储备记录
if _name_ == “__main__“:NameError: name ‘_name_‘ is not defined
chartjs自定义柱状图插件
有趣的opencv-记录图片二值化和相似度实现
5 款漏洞扫描工具:实用、强力、全面(含开源)
leetcode 1837. The sum of the digits in the K-base representation
Transformer怎么入门?如何学习Transformer?
力扣59-螺旋矩阵 II——边界判断
Markdown syntax









