LeetCode Power of Two (2的幂)
题意:判断1个数n是否刚好是2的幂,幂大于0。
思路:注意会给负数,奇数。对于每个数判断31次即可。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<||(n&)==&&n>) return false;
unsigned int t=;
while(t<n) //注意爆int
t<<=;
if(t==n) return true;
return false;
}
};
AC代码
一行代码,更巧的写法:
如果一个数n是2的某次幂,那么他应该是100000这样的,那么n-1会是0111111这样的,两者相与n&(n-1)必定为0。
class Solution {
public:
bool isPowerOfTwo(int n) {
return n> && !(n&(n-)) ;//100和011的&应该是0才对
}
};
AC代码
LeetCode Power of Two (2的幂)的更多相关文章
- C#LeetCode刷题之#342-4的幂(Power of Four)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4058 访问. 给定一个整数 (32 位有符号整数),请编写一个函 ...
- C#LeetCode刷题之#326-3的幂(Power of Three)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3867 访问. 给定一个整数,写一个函数来判断它是否是 3 的幂次 ...
- C#LeetCode刷题之#231-2的幂(Power of Two)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3858 访问. 给定一个整数,编写一个函数来判断它是否是 2 的幂 ...
- [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 Two
Given an integer, write a function to determine if it is a power of two. 题目意思: 给定一个整数,判断是否是2的幂 解题思路: ...
- 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 ...
随机推荐
- 计算器(delphi)
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...
- SecureCRT上传bash: rz: command not found(转载)
转载自:http://blog.csdn.net/zhangdaiscott/article/details/18141017 -bash: rz: command not found rz命令没找到 ...
- 插入排序(insertion_sort)
最简单的排序算法,又称插值排序,原理类似于打扑克牌时把摸到的牌插入手中已有序牌的过程. void insertion_sort(int* A ,int n){ int i,j,key; ;i < ...
- 【BZOJ3262】 陌上花开
Description 有n朵花,每朵花有三个属性:花形(s).颜色(c).气味(m),又三个整数表示.现要对每朵花评级,一朵花的级别是它拥有的美丽能超过的花的数量.定义一朵花A比另一朵花B要美丽,当 ...
- mybatis显示sql语句 log4j.properties配置文件
log4j.properties配置如下: 将ibatis log4j运行级别调到DEBUG可以在控制台打印出ibatis运行的sql语句,方便调试: ### 设置Logger输出级别和输出目的地 # ...
- Linux下使用GDB调试程序
问题描述: Linux下使用GDB调试程序 问题解决: (1)生成调试文件 注: 使用命令 gdb IOStream.c -o IOStre ...
- Matlab实现ItemBasedCF算法
感谢开源大神,慢慢收集资料.网上资料很少,我在找如何用matlab处理movielens数据集时找到的. 用ml-100k这个数据集,包括主函数和相似度函数. 代码托管于CSDN.
- secureCRT中文字符乱码
1.远程linux机器.修改环境变量LANG.例如在~/.bash_profile里面添加 export LANG=zh_CN.UTF8 2.本地windows机器.修改SecureCRT的设置.找到 ...
- setjump 和 longjump
goto语句可以用于同一个函数内异常处理,不幸的是,goto是本地的,它只能跳到所在函数内部的标号上.为了解决这个限制,C函数库提供了setjmp()和longjmp()函数,它们分别承担非局部标号和 ...
- 在WIN32 DLL中使用MFC
最近用WIN32 DLL,为了方便要用到MFC的一些库,又不想转工程,就网上找了很多方法,发现没有详细的介绍,有的也行不通,现在成功在WIN32 DLL中使用了MFC,记录一下以防以后用到忘记 一.修 ...