Leetcode 693. Binary Number with Alternating Bits

时间:2022-06-22
本文章向大家介绍Leetcode 693. Binary Number with Alternating Bits,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82429286

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

1. Description

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/