【leetcode】 Power of Two
2015-12-03 17:23
405 查看
描述:
Given an integer, write a function to determine if it is a power of two.
分析:
判断一个数是否是2的幂,判断方法主要依据2的N次幂的特点:仅有首位为1,其余各位都为0.
解决方案1:
(n&(n-1))==0
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0 && (n&(n-1))==0);
}
};
解决方案2:
所有位中只有1个1
class Solution {
public:
bool isPowerOfTwo(int n) {
int count = 0;
while (n > 0)
{
count+=(n&0x01);
n>>=1;
}
return count==1;
}
};
Given an integer, write a function to determine if it is a power of two.
分析:
判断一个数是否是2的幂,判断方法主要依据2的N次幂的特点:仅有首位为1,其余各位都为0.
解决方案1:
(n&(n-1))==0
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0 && (n&(n-1))==0);
}
};
解决方案2:
所有位中只有1个1
class Solution {
public:
bool isPowerOfTwo(int n) {
int count = 0;
while (n > 0)
{
count+=(n&0x01);
n>>=1;
}
return count==1;
}
};
相关文章推荐
- Linux学习笔记(8)之Shell编程入门--输入输出、引号
- C++primer plus第六版课后编程练习答案13.3
- android sqlite 的架构和语法
- mysql中如何判断当前是字符 mysql判断字段中有无汉字
- PCA主成分分析学习
- 专业程序员必习:最牛B的编码套路
- 3.python学习笔记:python下的多进程与多线程(一)
- 向量
- 嵌入式系统内存泄漏检测
- Shell: how to list all db links in oracle DB to generate a flat file (生成dblink列表文件)
- 查看分区表中分区详细信息
- Oracle 12c创建用户container参数
- 2015杭电新生赛1007油菜花王国【并查集】【图论】
- Linux学习笔记(六、链接命令)
- Ubuntu 15.10使用——系统安装
- SequenceInputStream
- Java面向对象编程-第8章学习笔记
- SequenceInputStream
- Java web 调试技巧之查看浏览器中调试中的network
- jquery 农历日历 可自适应