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 ...
随机推荐
- 1080. Graduate Admission (30)
时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue It is said that in 2013, there w ...
- [摘] SQLPLUS Syntax
You use the SQLPLUS command at the operating system prompt to start command-line SQL*Plus: SQLPLUS [ ...
- linq and rest api in sharepoint
//1.make sure your application using the .net fromwork 3.5 //2.create entity classes using the instr ...
- webx学习笔记
Webx学习笔记周建旭 2014-08-01 Webx工作流程 图 3.2. Webx Framework如何响应请求 当Webx Framework接收到一个来自WEB的请求以后,实际上它主要做了两 ...
- 对.net orm工具Dapper在多数据库方面的优化
Dapper是近2年异军突起的新ORM工具,它有ado.net般的高性能又有反射映射实体的灵活性,非常适合喜欢原生sql的程序员使用,而且它源码很小,十分轻便.我写本博客的目的不是为了介绍Dapper ...
- NSFileManager 沙盒文件管理
文件夹创建,复制,移动,删除,检查是否存在,代码如下: 1.获取沙盒 document 路径,作为文件夹路径的基路径. NSString *document = NSSearchPathForDire ...
- 让Flash背景透明兼容Firefox、IE 6和IE 7的代码
添加代码: <param name="wmode" value="transparent" > 到 <object>…</obje ...
- MFC线程钩子和全局钩子[HOOK DLL]
第一部分:API函数简介 1. SetWindowsHookEx函数 函数原型 HHOOK SetWindowsHookEx( int idHook, // hook typ ...
- 【leetcode】Palindrome Number (easy)
Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negativ ...
- SaaS系列介绍之四:我国SaaS市场发展
1 引言 那些没有经验的问题解决者们,几乎无一例外,都是去匆忙地寻找解决办法,而不是先给要解决的问题下定义. ...