Given an integer, write a function to determine if it is a power of two.

Example 1:

Input: 1
Output: true

Example 2:

Input: 16
Output: true

Example 3:

Input: 218
Output: false

给一个整数,写一个函数来判断它是否为2的次方数。

利用计算机用的是二进制的特点,用位操作,此题变得很简单。

2的n次方的特点是:二进制表示中最高位是1,其它位是0,

1  2   4     8     16    ....

1 10 100 1000 10000 ....

解法:位操作(Bit Operation),用右移操作,依次判断每一位的值,如果只有最高位是1,其余位都是0,则为2的次方数。

解法2: 位操作(Bit Operation),原数减1,则最高位为0,其余各位都变为1,把两数相与,就会得到0。

解法3: 用数学函数log

Java:

public boolean isPowerOfTwo(int n) {
if(n<=0)
return false; while(n>2){
int t = n>>1;
int c = t<<1; if(n-c != 0)
return false; n = n>>1;
} return true;
}  

Java:

public boolean isPowerOfTwo(int n) {
return n>0 && (n&n-1)==0;
}  

Java:

public boolean isPowerOfTwo(int n) {
return n>0 && n==Math.pow(2, Math.round(Math.log(n)/Math.log(2)));
} 

Python:

class Solution:
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
return n > 0 and (n & (n - 1)) == 0

Python:

class Solution2:
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
return n > 0 and (n & ~-n) == 0  

C++:

class Solution {
public:
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
};  

C++:

class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};

  

类似题目:

[LeetCode] Number of 1 Bits

[LeetCode] Power of Four

[LeetCode] 326. Power of Three

All LeetCode Questions List 题目汇总

最新文章

  1. windows下命令行打jar包方法
  2. IIS7 HTTPS 绑定主机头
  3. Mac功夫——OS X应用技巧
  4. html中offsetTop、clientTop、scrollTop、offsetTop
  5. php xml转为xml或者json
  6. U8记账凭证修改方法汇总
  7. MEF学习笔记
  8. 如何在IIS 中配置应用程序(Convert to Application)?
  9. asm文件开头的assume意义
  10. python爬虫实践(二)——爬取张艺谋导演的电影《影》的豆瓣影评并进行简单分析
  11. 关于vue中this.attr代替this.data.attr访问的原理
  12. Labview笔记-创建自定义控件
  13. 详解javascript立即执行函数表达式(IIFE)
  14. 1、JPA-HelloWorld
  15. 解决IE6下透明图片有背景的问题
  16. 匹配追踪算法(MP)简介
  17. WEB入门.九 导航菜单
  18. JAVA复制文件最快的算法
  19. 如何使用Android MediaStore裁剪大图片
  20. Tomcat最大连接数问题

热门文章

  1. scrapy框架用CrawlSpider类爬取电影天堂.
  2. python爬虫中的ip代理设置
  3. 在Windows10系统下安装Oracle 11g数据库
  4. Vue移动端项目如何使用手机预览调试
  5. 前端知识--控制input按钮的可用和不可用
  6. Windbg命令的语法规则系列(二)
  7. Noip 2017 题目整理
  8. 75: libreoj #10028 双向宽搜
  9. Tex家族关系
  10. 读入优化&amp;输出优化