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

按照要求check

class Solution {
    public boolean hasAlternatingBits(int n) {
        if(n <= 0)
            return false;

        int firstOne = 31;
        for(; firstOne >= 0; firstOne--) {
            if(((n >> firstOne) & 1) == 1) {
                break;
            }
        }

        int check = 1;
        for(int i = firstOne; i >= 0; i--) {
            int bit = (n >> i) & 1;

            if(bit != check) 
                return false;

            check = 1 - check;
        }

        return true;
    }
}

results matching ""

    No results matching ""