当前位置:网站首页>Leetcode-231-2的幂
Leetcode-231-2的幂
2022-07-07 13:53:00 【_春天_】
题目描述
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
解题思路
判断一个整数是否是2的幂次方,可以利用2的幂次方的特性,把数字变成二进制来看。
我们知道,如果一个数字n是2的幂次方,那么它的二进制表示必定首位为1,其余位为0。而n-1的二进制表示中,首位变成了0,其余位是1.
例如,下图代表n=16时的二进制表示:
| …… | 2 4 2^{4} 24 | 2 3 2^{3} 23 | 2 2 2^{2} 22 | 2 1 2^{1} 21 | 2 0 2^{0} 20 |
|---|---|---|---|---|---|
| n=16 | 1 | 0 | 0 | 0 | 0 |
| n=15 | 0 | 1 | 1 | 1 | 1 |
&运算的特点是,相同为1,不同为0
这样的话,n和n-1做和运算(&),每位都是0&1,结果必然是0
也就是说如果n是2的幂次方,则n&(n-1)=0
如果n不是2的幂次方,结果则大于0
因此,利用&运算来判断
代码
代码一:正向计算
先贴上我2min之内完成的代码(laji code
import math
def isPowerOfTwo(self, n):
p = 0
if n <= 0:
return False
while True:
num = math.pow(2, p)
if n < num:
return False
elif n == num:
return True
else:
p += 1
continue
代码二:反向计算
def isPowerOfTwo(self, n):
if n:
while n % 2 == 0 :
n /= 2
return n == 1
return False
代码一和代码二的效率一样(一样低)
代码三:别人家的代码
def isPowerOfTwo(self, n):
if n < 1:
return False
return not (n & (n-1))
简洁明了,高效舒服。
边栏推荐
- asyncio 概念和用法
- Three. JS introductory learning notes 07: external model import -c4d to JSON file for web pages -fbx import
- 深度之眼(六)——矩阵的逆(附:logistic模型一些想法)
- Three. JS introductory learning notes 11:three JS group composite object
- Three. JS introductory learning notes 04: external model import - no material obj model
- numpy---基础学习笔记
- 无线传感器网络--ZigBee和6LoWPAN
- Summary of knowledge points of xlua hot update solution
- Dotween -- ease function
- Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
猜你喜欢

OpenGL's distinction and understanding of VAO, VBO and EBO

webgl_ Enter the three-dimensional world (2)

一大波开源小抄来袭

SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术

Three. JS introductory learning notes 03: perspective projection camera

Three. JS introductory learning notes 08:orbitcontrols JS plug-in - mouse control model rotation, zoom in, zoom out, translation, etc

分步式監控平臺zabbix

MySQL数据库基本操作-DQL-基本查询

Three. JS introductory learning notes 19: how to import FBX static model

Async and await
随机推荐
Syntaxhighlight highlights the right scroll bar
Using eating in cocos Creator
47_Opencv中的轮廓查找 cv::findContours()
Unity drawing plug-in = = [support the update of the original atlas]
Aerospace Hongtu information won the bid for the database system research and development project of a unit in Urumqi
Getting started with webgl (2)
webgl_ Enter the three-dimensional world (2)
安科瑞电网智能化发展的必然趋势电力系统采用微机保护装置是
PyTorch 中的乘法:mul()、multiply()、matmul()、mm()、mv()、dot()
星瑞格数据库入围“2021年度福建省信息技术应用创新典型解决方案”
SPI master RX time out interrupt
nodejs package. JSON version number ^ and~
山东老博会,2022中国智慧养老展会,智能化养老、适老科技展
用手机在通达信上开户靠谱吗?这样炒股有没有什么安全隐患
LeetCode2_ Add two numbers
121. 买卖股票的最佳时机
神经网络c语言中的指针是怎么回事
Limit of total fields [1000] in index has been exceeded
Xingruige database was shortlisted as the "typical solution for information technology application and innovation in Fujian Province in 2021"
招标公告:2022年云南联通gbase数据库维保公开比选项目(第二次)比选公告