정수 n이 있다고 가정합시다. 문제는 이 정수가 이진법에 상응하는 대체 패턴을 가지고 있는지 여부를 확인하는 것입니다. 대체 패턴은 101010…을 의미합니다.
접근 방식은 다음과 같습니다. 이진수 등가를 사용하여 각 숫자를 확인하고 연속되는 두 숫자가 같으면 false를 반환하고 그렇지 않으면 true를 반환합니다.
예시
#include <iostream>
using namespace std;
bool hasAlternatePattern(unsigned int n) {
int previous = n % 2;
n = n/2;
while (n > 0) {
int current = n % 2;
if (current == previous) // If current bit is same as previous
return false;
previous = current;
n = n / 2;
}
return true;
}
int main() {
unsigned int number = 42;
if(hasAlternatePattern(number))
cout << "Has alternating pattern";
else
cout << "Has no alternating pattern";
} 출력
Has alternating pattern