Leetcode Power of Two
Given an integer, write a function to determine if it is a power of two.
题目意思:
给定一个整数,判断是否是2的幂
解题思路:
如果一个整数是2的幂,则二进制最高位为1,减去1后则最高位变为0,后面全部是1,相与判读是否为零,注意负数和0,负数的最高位是1。
更多二进制的问题可以参考《编程之美》中二进制有多少个1,面试时容易问。
源代码:
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > ) && (n&(n-)==);
}
};
Leetcode Power of Two的更多相关文章
- [LeetCode] Power of Four 判断4的次方数
Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Gi ...
- [LeetCode] Power of Three 判断3的次方数
Given an integer, write a function to determine if it is a power of three. Follow up:Could you do it ...
- [LeetCode] Power of Two 判断2的次方数
Given an integer, write a function to determine if it is a power of two. Hint: Could you solve it in ...
- LeetCode Power of Four
原题链接在这里:https://leetcode.com/problems/power-of-four/ 题目: Given an integer (signed 32 bits), write a ...
- LeetCode Power of Three
原题链接在这里:https://leetcode.com/problems/power-of-three/ 与Power of Two类似.检查能否被3整除,然后整除,再重复检查结果. Time Co ...
- Leetcode Power of two, three, four
Given an integer, write a function to determine if it is a power of two. Hint: Could you solve it in ...
- leetcode power(x,n)
class Solution { public: double pow(double x, int n) { double a=1; if(n==0)return 1; if(x==1)return ...
- LeetCode——Power of Two
Description: Given an integer, write a function to determine if it is a power of two. public class S ...
- [LeetCode]Power of N
题目:Power of Two Given an integer, write a function to determine if it is a power of two. 题意:判断一个数是否是 ...
随机推荐
- 在XP上运行IIS5.1新建站点
系统问题,XP下IIS5.1不能直接新建站点,因为内核限制只能同时运行一个站点,要想新建站点,必须把当前站点停掉,然后用adsutil.vbs脚本创建,脚本在C:\Inetpub\AdminScrip ...
- enum 与 enum class
c++11中引入了新的枚举类型---->强制枚举类型 // unscoped enum: enum [identifier] [: type] {enum-list}; // scoped e ...
- Lr中关于字符串的截取
Action() { char separators[] = "\"processId\":\"";//截取条件 char * token; char ...
- Activity系列讲解---数据传递
在Android中,不同的Activity实例可能运行在一个进程中,也可能运行在不同的进程中.因此需要一种特别的机制帮助我们在Activity之间传递消息.Android中通过Intent对象来表示一 ...
- C/C++: C++变量和基本类型
1. 如何选择类型的准则 当明确知晓数值不可能为负的时候,应该选择无符号类型. 使用int执行整数运算的时候,在实际应用中,short常常显得太小而long一般和int有一样的尺寸,如果数值超过了in ...
- 安装yum
RedHat 安装配置 YUM 删除 1 . 查询系统是否安装 yum : rpm – qa|grep yum 2删除原有 yum rpm -qa|grep yum|xargs rpm -e – no ...
- IE8下导入EXCEL数据传到客户端以附件下载
IE8下导入EXCEL数据传到客户端以附件下载方式出现,而不显示数据,解决方法:以text/html格式返回. HttpResponseMessage message = new HttpRespon ...
- Ruby数组
Ruby数组是有序的,任何对象的整数索引的集合.每个数组中的元素相关联,并提取到的一个索引.下标与C或Java相似,从0开始.负数索引假设数组末尾,也就是说-1表示最后一个元素的数组索引,-2是数组中 ...
- LInux Shell 快捷键
CTRL 键相关的快捷键: Ctrl + a - Jump to the start of the lineCtrl + b - Move back a charCtrl + c - Terminat ...
- 何为HDFS?
该文来自百度百科,自我收藏. Hadoop分布式文件系统(HDFS)被设计成适合运行在通用硬件(commodity hardware)上的分布式文件系统.它和现有的分布式文件系统有很多共同点.但同时, ...