반응형
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;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 728. Self Dividing Numbers.cpp (0) | 2023.06.26 |
---|---|
(C++) - LeetCode (easy) 709. To Lower Case (0) | 2023.06.21 |
(C++) - LeetCode (easy) 682. Baseball Game (0) | 2023.06.12 |
(C++) - LeetCode (easy) 671. Second Minimum Node In a Binary Tree (0) | 2023.06.09 |
(C++) - LeetCode (easy) 661. Image Smoother (0) | 2023.06.05 |