본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 693. Binary Number with Alternating Bits

반응형

https://leetcode.com/problems/binary-number-with-alternating-bits/description/

 

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

이진법 변환 구현 문제였습니다.

📕 풀이방법

📔 풀이과정

1. 십진수 n을 2진수로 변환해 문자열로 반환하는 getBinString함수를 구현해줍니다. 인접 원소 끼리만을 비교할 예정이므로 뒤집힌 문자열을 반환해도 무방합니다.

2. 문자열 변수 bin을 선언해 함수 반환값을 받아줍니다. 

📔 정답 출력 | 반환

이후 bin의 원소들을 순회하며 인접한 원소가 같다면 return false해줍니다.

loop가 끝나면 바로 true를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    string getBinString(int n) {
        string bin;
        while(n) {
            bin += to_string(n % 2);
            n /= 2;
        }
        return bin;
    }
    bool hasAlternatingBits(int n) {
        string bin = getBinString(n);
        for(int i = 0; i < bin.size() - 1; i++) {
            if(bin[i] == bin[i+1]) return false;
        }
        return true;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.