zoukankan      html  css  js  c++  java
  • [LeetCode]63. Power of Two 2的幂次

    Given an integer, write a function to determine if it is a power of two.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     
    解法1:通过每次都判断n的最后一位是否是1来统计1的个数。注意n>0的必要条件。而n<=0则必定不是2的幂次了。
    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            int cnt = 0;
            while(n > 0) {
                cnt += n & 0x01;
                n >>= 1;
            }
            return cnt == 1;
        }
    };
    解法2:通过每次判断n的某一位来统计1的个数。注意只能在n>0的情况下起作用(在n=INT_MIN时恰好也只有一个1)。
    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            if(n <= 0) return false;
            unsigned int mask = 0x01, loop = sizeof(int) * 8, cnt = 0;
            for (int i = 0; i < loop; ++i) {
                if ((n & mask) != 0)
                    ++cnt;
                mask <<= 1;
            }
            return cnt == 1;
        }
    };

    解法3:把一个整数减去1,再和原整数做与运算,可以把该整数的最后一个1变为0.这个过程循环进行到某一步时会将该整数清零。因此这也可以统计其中1的个数。

    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            int cnt = 0;
            while (n > 0) {
                n &= n - 1;
                ++cnt;
            }
            return cnt == 1;
        }
    };

    解法4:不需要统计其二进制表示中1的个数。2的幂次表示为二进制必是最高位为1,其他位为0(不算前面填充的0)。因此减去1后最高位为0而其他位变为1,于是两数按位与得到0。

    class Solution {
    public:
        bool isPowerOfTwo(int n) {
            return n > 0 && !(n & n - 1);
        }
    };

    其他的统计一个整数的二进制表示中有多少个1的方法http://www.cnblogs.com/aprilcheny/p/4943560.html

  • 相关阅读:
    基于fis的前端模块化和工程化方案
    网页中font-family的属性解析
    centos 基础环境配置
    golang的各种数据格式的互相转换
    golang 的编译安装以及supervisord部署
    ip地址库选择
    golang中使用mongodb的操作类以及如何封装
    golang中使用mongodb
    golang使用sqlite
    centos 安装nginx
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4943552.html
Copyright © 2011-2022 走看看