美文网首页Leetcode
Leetcode 693. Binary Number with

Leetcode 693. Binary Number with

作者: SnailTyan | 来源:发表于2018-09-05 19:28 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Binary Number with Alternating Bits

    2. Solution

    • Version 1
    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            vector<int> bits;
            while(n) {
                bits.push_back(n & 1);
                n >>= 1;
            }
            for(int i = 0; i < bits.size() - 1; i++) {
                if(bits[i] == bits[i + 1]) {
                    return false;
                }
            }
            return true;
        }
    };
    
    • Version 2
    class Solution {
    public:
        bool hasAlternatingBits(int n) {
            int pre = - 1;
            while(n) {
                int current = n & 1;
                if(pre != -1 && pre == current) {
                    return false;
                }
                n >>= 1;
                pre = current;
            }
            return true;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/binary-number-with-alternating-bits/description/

    相关文章

      网友评论

        本文标题:Leetcode 693. Binary Number with

        本文链接:https://www.haomeiwen.com/subject/kirzwftx.html