서하아빠의 개발 블로그

693. Binary Number with Alternating Bits 본문

알고리즘/LeetCode

693. Binary Number with Alternating Bits

서하아빠 2021. 4. 20. 22:59

693. Binary Number with Alternating Bits

Easy

 

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
Explanation: The binary representation of 5 is: 101

Example 2:

Input: n = 7 
Output: false 
Explanation: The binary representation of 7 is: 111.

Example 3:

Input: n = 11 
Output: false 
Explanation: The binary representation of 11 is: 1011.

Example 4:

Input: n = 10 
Output: true 
Explanation: The binary representation of 10 is: 1010.

Example 5:

Input: n = 3 
Output: false

 

Constraints:

  • 1 <= n <= 231 - 1

[문제풀이]

1) 주어진 값을 2진수로 변환한다. 

2) 이때 주어진 값(n)을 1보다 작을 때까지 계속 2로 나누어서,

   이전 나머지 값과 현재 나머지 값이 같으면 => false

   이전 나머지 값과 현재 나머지 값이 다르면 => true

 

[소스코드]

class Solution {
    public boolean hasAlternatingBits(int n) {
        if( n <=1 ) return true;
        
        int prev = n % 2;
        n /= 2;
        while( n >= 1 ) {
            int cur = n % 2;
            if( prev == cur) {
                return false;
            } 
            n /= 2;
            prev = cur;
        }
        return true;
    }
}

   

'알고리즘 > LeetCode' 카테고리의 다른 글

217. Contains Duplicate  (0) 2022.05.20
25. Reverse Nodes in k-Group  (0) 2022.05.20
61. Rotate List  (0) 2022.05.19
200. Number of Islands  (0) 2021.06.14
283. Move Zeroes  (0) 2021.04.07