[LeetCode] Binary Number with Alternating Bits

아르당·2026년 2월 15일

LeetCode

목록 보기
151/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

양의 정수가 주어졌을 때, 인접한 두 비트가 항상 서로 다른 값을 갖는 교대 비트가 있는지 확인해라.

Example

#1
Input: n = 5
Output: true
Explanation: 숫자 5의 이진 표현은 101이다.

#2
Input: n = 7
Output: false
Explanation: 숫자 7의 이진 표현은 111이다.

#3
Input: n = 11
Output: false
Explanation: 숫자 11의 이진 표현은 1011이다.

Constraints

  • 1 <= n <= 2^31 - 1

Solved

class Solution {
    public boolean hasAlternatingBits(int n) {
        n = n ^ (n >> 1);

        return (n & n + 1) == 0;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글