LeetCode 231 Power of Two(三解)
2016-03-28 23:37
190 查看
231.
Power of Two
Given an integer, write a function to determine if it is a power of two.
我的方法是暴力求解,循环让1一直乘以2,如果结果等于n,且n大于0则输出true。这是最容易想到的方法
class Solution {
public:
bool isPowerOfTwo(int n) {
int result=1;
for(int i=0;i!=1000;i++)
{
if(result==n &&n>0)
{
return true;
}
result*=2;
}
return false;
}
};搜索网上的资料发现更巧妙的方法,利用到了十六进制的特点(2的N次幂的特点:仅有首位为1,其余各位都为0.)
class Solution {
public:
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
};
或者
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};
Power of Two
Given an integer, write a function to determine if it is a power of two.
我的方法是暴力求解,循环让1一直乘以2,如果结果等于n,且n大于0则输出true。这是最容易想到的方法
class Solution {
public:
bool isPowerOfTwo(int n) {
int result=1;
for(int i=0;i!=1000;i++)
{
if(result==n &&n>0)
{
return true;
}
result*=2;
}
return false;
}
};搜索网上的资料发现更巧妙的方法,利用到了十六进制的特点(2的N次幂的特点:仅有首位为1,其余各位都为0.)
class Solution {
public:
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
};
或者
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};
相关文章推荐
- 无线键盘的安全性分析与探究
- StatePattern
- 【java】 java 集合类UML图
- 大整数加减乘除 c实现
- UVA679
- Android程序员的技术要求和学习路线
- 当你不优秀的时候,就让自己具有一些优秀的特质
- Spring装配Bean的过程
- JavaScript面向对象程序设计
- MySQL sql语句优化(转)
- HashTable和HashMap的区别
- 【杭电oj】1495 - 非常可乐(bfs,队列)
- C++中类的多态与虚函数
- jquery插件教程
- Myeclipse10破解步骤
- iOS: 聊聊 Designated Initializer(指定初始化函数)
- 第五周上机实践项目——项目3-时间类(2)
- 创建一个集合图像
- hdu-1247 Hat’s Words(字典树)
- 第七届蓝桥杯C语言B组题目之凑算式