zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Number with Alternating Bits

    Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

    Example 1:

    Input: 5
    Output: True
    Explanation:
    The binary representation of 5 is: 101

    Example 2:

    Input: 7
    Output: False
    Explanation:
    The binary representation of 7 is: 111.

    Example 3:

    Input: 11
    Output: False
    Explanation:
    The binary representation of 11 is: 1011.

    Example 4:

    Input: 10
    Output: True
    Explanation:
    The binary representation of 10 is: 1010.

    判断一个数字的二进制是否是01交替出现的。直接循环按位与1即可,如果是交替出现,则每次结果都不同,如果出现相同的结果,返回false即可。

    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            int a = 0, b = 0, bit = 1;
            while (n) {
                a = n & bit;
                n >>= 1;
                b = n & bit;
                if (a == b)
                    return false;
            }
            return true;
        }
    };
    // 6 ms
  • 相关阅读:
    Boost.Asio c++ 网络编程翻译(10)
    建站手册:网站品质
    建站手册-template
    CDN:分类
    CDN:BootCDN 项目列表-摘录-20180405
    CDN:BootCDN
    CDN:目录
    CDN-template
    JavaScript-Tool:md5.js
    Regexp-Utils:基本
  • 原文地址:https://www.cnblogs.com/immjc/p/7643151.html
Copyright © 2011-2022 走看看