题意:判断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的幂)的更多相关文章

  1. C#LeetCode刷题之#342-4的幂(Power of Four)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4058 访问. 给定一个整数 (32 位有符号整数),请编写一个函 ...

  2. C#LeetCode刷题之#326-3的幂(Power of Three)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3867 访问. 给定一个整数,写一个函数来判断它是否是 3 的幂次 ...

  3. C#LeetCode刷题之#231-2的幂(Power of Two)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3858 访问. 给定一个整数,编写一个函数来判断它是否是 2 的幂 ...

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. Leetcode Power of Two

    Given an integer, write a function to determine if it is a power of two. 题目意思: 给定一个整数,判断是否是2的幂 解题思路: ...

  8. LeetCode Power of Four

    原题链接在这里:https://leetcode.com/problems/power-of-four/ 题目: Given an integer (signed 32 bits), write a ...

  9. LeetCode Power of Three

    原题链接在这里:https://leetcode.com/problems/power-of-three/ 与Power of Two类似.检查能否被3整除,然后整除,再重复检查结果. Time Co ...

随机推荐

  1. Beaglebone Back学习七(URAT串口测试)

    URAT串口测试

  2. asp.net 运行时, 报控件不存在

    Asp.net 运行时,报控件不存在,但系统中确实加入了控件z, 但是生成网站的时候,报控件不存在,输入代码的时候,this.edtxx.Text 确实可以输入 原因: 系统修改的时候,作了一个备份, ...

  3. Kinetic使用注意点--collection

    new Collection() 扩展了数组,主要用于配合new Container().get()使用 方法: each(func):遍历数组,执行回调函数.回调函数接收两个值,节点和索引. toA ...

  4. MVC-HtmlHelper扩展

    1.添加对System.Web.Mvc的引用 2.添加一个静态类,里面的扩展方法也必须是静态的 //HtmlHelper扩展类 //添加对System.Web.Mvc的引用 //命名空间:System ...

  5. SPFA&邻接表 PASCAL

    题目来自CODE[VS]-->热浪 1557 热浪 时间限制: 1 s 空间限制: 256000 KB 题目等级 : 钻石       题目描述 Description 德克萨斯纯朴的民眾们这个 ...

  6. Xcode文档下载与安装路径

    https://developer.apple.com/library/downloads/docset-index.dvtdownloadableindex ~/Library/Developer/ ...

  7. 预告:准备开个坑,集中学习一下esp32模块

    对这个模块有兴趣的可以关注我以后的更新,寒假会抽空写几篇心得.

  8. 【链表】BZOJ 2288: 【POJ Challenge】生日礼物

    2288: [POJ Challenge]生日礼物 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 382  Solved: 111[Submit][S ...

  9. 认识OD的两种断点

    OllyDBG从原理上来区分,有两种不同的断点:软件断点和硬件断点. 也许会有朋友说那不是还有内存断点吗? 内存断点严格来说是属于一种特殊的软件断点. 内存断点: 内存断点每次只能设置一个,假如你设置 ...

  10. 16进制字符串转数字(C/C++,VB/VB.net,C#)

    这个问题看是很简单,但是在不同语言中实现的方式却千差万别,如果不知道方法,还真是麻烦,我就是在C#中遇到该问题,让我费了很大的周折,才在msdn查到. 一.16进制字符串转数字      1.C/C+ ...