LeetCode知识点总结 - 693

阅读 34

2022-01-16

LeetCode 693. Binary Number with Alternating Bits

考点难度
Bit ManipulationEasy
题目

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

思路

判断n/2n%2是不是一样。

答案
public boolean hasAlternatingBits(int n) {
        int cur = n % 2;
        n /= 2;
        while (n > 0) {
            if (cur == n % 2) return false;
            cur = n % 2;
            n /= 2;
        }
        return true;
}

精彩评论(0)

0 0 举报