231. Power of Two
来源:互联网 发布:金麦汽修软件 编辑:程序博客网 时间:2024/05/16 01:11
Given an integer, write a function to determine if it is a power of two.
题意:给一个整数,写一个函数判读它是不是2的幂
思路1:可以直接除以2,知道余数为0,或者1,余数是0则是2的幂,否则不是
思路2:这里可以用位运算进行解决,如果是2的幂,则其二进制表示一定是‘10000....’,让其与(n-1)二进制为'1111....'求与运算,结果肯定是0,如结果不是0,则其不是2的幂(这里题目中没有说该数为正整数,所以要做一个判断,小于等于0的数都不是2的幂)
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n>0 and n & (n-1) == 0:
return True
else:
return False
(这里有个小问题,为什么python用位运算提交代码,运行效率并不高呢?提交多次,运行时间都比大部分人都运行时间要长。)
0 0
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- fig7.5.cpp
- jquery操作dom
- 【网络】最详细的 HTTPS 介绍
- Android:你不知道的 WebView 使用漏洞
- GoldenDict字典Snap应用
- 231. Power of Two
- Java多维数组
- 【网络】详解https是如何确保安全的?
- mybatis中mysql多条件查询
- Excel Txt 字符集设置
- 03.Ajax的使用四大步骤
- ASP.NET MVC 表单提交数组和泛型集合的方法
- mssql常用sql语句案例,亲测可用,复习必备
- 如何使用Eclipse进行jar包调试