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. Webstorm 2016.3激活码

    webstorm 2016.3 可用激活码, 使用activation code方式激活 就这么任性,就这么长 43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKI ...

  2. -webkit-box-flex被内容撑开了

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  3. BZOJ 2160: 拉拉队排练

    Description 问长度前 \(k\) 大的奇长度回文子串的乘积. Sol Manacher. 直接马拉车跑一边,统计一下答案,每次将长度-2就可以了. Code /************** ...

  4. [CodeWars][JS]如何判断给定的数字是否整数

    问题描述: We are asking for a function to take a positive integer value, and return a list of all positi ...

  5. linux 比较两个文件是否一致

    diff source target 如果一致不弹出任何信息

  6. xtrabackup 使用说明(续)

    背景: 关于物理备份工具xtrabackup的一些说明可以先看之前写过的文章说明:xtrabackup 安装使用.现在xtrabackup版本升级到了2.4.4,相比之前的2.1有了比较大的变化:in ...

  7. RecyclerView的使用之多种Item加载布局

    精益求精,为了更加透彻熟练得掌握,本文再次给大家介石介绍下如何利用RecyclerView实现多Item布局的加载,多Item布局的加载的意思就是在开发过程中List的每一项可能根据需求的不同会加载不 ...

  8. 利用代码添加autolayout约束

    1.概述 通常我们通过storyboard能够完成的,代码也能够完成,所以这里介绍下代码实现约束的添加,通常我们不这么干(在不使用第三方框架的情况下,使用系统自带的类添加约束特别繁琐),所以这里仅仅简 ...

  9. MySQL重置root密码

    1,以管理员身份进入cmd命令行,输入命令:Net stop mysql; 2 ,进入mysql安装目录的bin文件夹下,执行mysqld --skip-grant-tables  启动MySQL S ...

  10. 【转】Caffe初试(七)其它常用层及参数

    本文讲解一些其它的常用层,包括:softmax-loss层,Inner Product层,accuracy层,reshape层和dropout层及它们的参数配置. 1.softmax-loss sof ...