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的更多相关文章

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

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

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

  4. LeetCode Power of Four

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

  5. LeetCode Power of Three

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

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

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

  8. LeetCode——Power of Two

    Description: Given an integer, write a function to determine if it is a power of two. public class S ...

  9. [LeetCode]Power of N

    题目:Power of Two Given an integer, write a function to determine if it is a power of two. 题意:判断一个数是否是 ...

随机推荐

  1. Maven的POM.xml配置大全

    <?xml version="1.0" encoding="utf-8"?> <project xmlns="http://mave ...

  2. 【HEOI2012】采花 BZOJ2743

    Description 萧芸斓是Z国的公主,平时的一大爱好是采花. 今天天气晴朗,阳光明媚,公主清晨便去了皇宫中新建的花园采花.花园足够大,容纳了n朵花,花有c种颜色(用整数1-c表示),且花是排成一 ...

  3. nginx配置反向代理解决前后端分离跨域问题

    摘自<AngularJS深度剖析与最佳实践>P132 nginx配置文件如下: server { listen ; server_name your.domain.name; locati ...

  4. EFUpdate

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  5. QL Server 2008 所有账号丢失sysadmin权限,sa账号亦没有开启,该如何解决??

    1. 用Run as a administrator打开命令提示符里输入NET STOP MSSQLSERVER, 即停止MSSQLSERVER运行. 2. 在命令提示符里输入 NET START M ...

  6. Firefox Portable Developer 52.0.0.6176-6178

    FirefoxPortableDeveloper-52.0.0.6176.7z 47.9 MB FirefoxPortableDeveloper-52.0.0.6178.7z 55.8 MB

  7. centos6u3 安装 celery 总结

    耗时大概6小时. 执行 pip install celery 之后, 在 mac 上 celery 可以正常运行, 在 centos 6u3 上报错如下: Traceback (most recent ...

  8. nginx 反向代理 公用一个外网端口

    服务器:ubuntu 配置nginx代理有2个文件,分别是sites-enabled 和sites-available. 路径都在/etc/nginx下,sites-enabled为sites-ava ...

  9. linux vim 插入行号

    1 在文本中插入行号 最近有朋友提到某编辑器有一个可以插入行号的插件,问Vim有没有办法可以在文章中插入行号.%$^&*#8~#$@#!--让我们看一下有多少种方式可以在vim中插入行号或数字 ...

  10. JavaCV配置

    下载javacv-1.2-bin.zip https://github.com/bytedeco/javacv 解压 在Eclipse项目 Referenced Libraries 中 Add Ext ...