본문 바로가기
Problem Solving/LeetCode

[LeetCode] 693. Binary Number with Alternating Bits - Java

by graycode 2026. 9. 24.

• 문제 링크

 

Binary Number with Alternating Bits - LeetCode

Can you solve this real interview question? Binary Number with Alternating Bits - Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.   Example 1: Input: n = 5 Output: true Expla

leetcode.com

 

• 풀이 코드

public class Solution {

    public boolean hasAlternatingBits(int n) {
        n ^= (n >> 1);
        return (n & (n + 1)) == 0;
    }

}

댓글