[LeetCode] C++: Simple Question-Bit Operation 693. Alternate Bit Binary Number

693. Alternating Bit Binary Number

Easy 90

Given a positive integer, check whether its binary representation is always 0 and 1 alternately: in other words, the two adjacent digits in the binary representation are never the same.

 

Example 1:

Input: n = 5
 Output: true
 Explanation: The binary representation of 5 is: 101

Example 2:

Input: n = 7
 Output: false
 Explanation: The binary representation of 7 is: 111.

Example 3:

Input: n = 11
 Output: false
 Explanation: The binary representation of 11 is: 1011.

Example 4:

Input: n = 10
 Output: true
 Explanation: The binary representation of 10 is: 1010.

Example 5:

Input: n = 3
 Output: false

 

prompt:

  • 1 <= n <= 231 - 1

Bit operation + array 

class Solution {
public:
    bool hasAlternatingBits(int n) {
        uint32_t num = n;
        vector<int> vec;
        while(num != 0){
            vec.push_back(num & 1);
            num = num >> 1;
        }
        for(int i = 1; i < vec.size(); i++){
            if(vec[i] == vec[i-1]){
                return false;
            }
        }
        return true;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113773555
Recommended