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. oracle 关于null值排序

    在oracle中根据字段来desc排序的话null值可能会在数据的最前面.然而有时候我们查看数据的时候并不希望能够在前面看到这些null值的排序数据. 因此我查了一下: 1.排序的时候运用nvl(). ...

  2. MAC下apache+php

    mac下是自带有Apache和php的服务器的,不需要另外安装,本文就对相关配置进行介绍. 第一:Apache 在终端中输入,下面指令即可启动Apache服务器: //启动 sudo apachect ...

  3. ubuntu 搞坏了sudoers文件之修复方案

    pkexec visudo askubuntu原回答摘抄如下 On a modern Ubuntu system (and many other GNU/Linux distributions), f ...

  4. 高性能MySQL(二):创建高性能索引

    ) not null); insert into city_demo(city) select city from city insert into city_demo(city) select ci ...

  5. mysql nonInstall 版本的安装与配置

    最近用到mysql,发现如果想使用最新版本64 bit mysql 需要独特的配置和使用方式 结合最近的研究总结一下安装过程. 首先下载:http://dev.mysql.com/downloads/ ...

  6. 解决自定义Shiro.Realm扩展类不能用注解(@Resource或@Autowire)自动装配的问题

    问题产生原因:加载Realm时其他Spring配置文件(xml)尚未加载,导致注入失败. 解决方法:编写一个设置类把注入工作提前完成. package com.xkt.shiro import org ...

  7. set和map的简单用法

    .set(集合)map(映射)都属于关联类容器 都支持查询一个元素是否存在并能够有效地获取元素. set集合的元素总是从小到大排列,set集合通过二分查找树实现.它具备以下两个特点: ①:独一无二的元 ...

  8. Markdown 语法说明(持续更新-20160822)

    Markdown 是一种轻量级的「标记语言」.Markdown 语法的目标是:成为一种适用于网络的书写语言.Markdown 的语法简单,熟悉Markdown语法规则,事倍功半. 语法 插入图片如何定 ...

  9. WinForm BaseClass类常用通用方法

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  10. 在eclipse安装svn插件

    1.在“帮助--安装新软件”中选中.我这个是中文版的,英文版的是“install new software”