반응형
1. 문제
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
int solution(int N);
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..2,147,483,647].
정수 N(1 ~ 2,147,483,647)을 2진수로 표현했을 때, 가장 긴 0의 갯수를 구하는 문제이다.
예시)
| 10진수 | 2진수 | 가장 긴 0의 갯수 |
| 9 | 1001 | 2 |
| 529 | 1000010001 | 4 |
| 20 | 10100 | 1 |
| 15 | 1111 | 0 |
| 32 | 100000 | 0 |
2. 풀이전략
정수를 2진수로 변환하면서 0의 갯수를 센다.
(진법에 대한 글은 여기로)
3. 코드 (C++)
int solution(int N) {
bool start = false;
int binary_gap = 0;
int cnt = 0;
// 2진수 변환
while(N > 0)
{
if(N % 2 == 1) // 2진수 1
{
if(start == false) // 처음 만난 1
{
start = true; // 0을 카운트 하기 위해 flag를 true로 변경
cnt = 0; // 카운트 변수 초기화
}
else // 0을 카운트 하는 중간에 1을 만났다
{
//지금까지 카운트한 0이 가장 길다면, 저장
if(cnt > binary_gap) binary_gap = cnt;
cnt = 0; // 카운트 변수 초기화
}
}
else // 2진수 0
{
//start flag가 0일 때만 카운트한다. 아니면 1000같은 2진수도 카운팅 된다.
if(start == true) cnt++;
}
N /= 2;
}
return binary_gap;
}반응형
'Algorithm Problem > Codility' 카테고리의 다른 글
| Lesson 3. Time Complexity - PermMissingElem (0) | 2024.09.28 |
|---|---|
| Lesson 3. Time Complexity - FrogJmp (0) | 2024.09.28 |
| Lesson 2. Arrays - OddOccurrencesInArray #2 (속도 개선) (0) | 2024.09.25 |
| Lesson 2. Arrays - OddOccurrencesInArray #1 (0) | 2024.09.25 |
| Lesson 2. Arrays - CyclicRotation (0) | 2024.09.21 |