1. 程式人生 > >693. Binary Number with Alternating Bits - LeetCode

693. Binary Number with Alternating Bits - LeetCode

bin AS als 返回 question nat tco ref RR

Question

693.?Binary Number with Alternating Bits

技術分享圖片

Solution

思路:輸入一個整數,它的二進制01交替出現,遍歷其二進制字符串,下一個與上一個不等,返回true,如果有相等的就返回false

Java實現:

public boolean hasAlternatingBits(int n) {
    char last = '2'; // 非0非1即可
    for (char c : Integer.toBinaryString(n).toCharArray()) { // int轉二進制字符串
        if (c == last) return
false; last = c; } return true; }

693. Binary Number with Alternating Bits - LeetCode