Task desciption
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:
def solution(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이라는 정수를 주고 2진수로 변환한 뒤 1들 사이에 0이 가장 많은 경우를 찾는 문제입니다.
예를 들어 8이라는 수는 2진수로 변환하면 1001이 되고 1 사이에 0이 2개이므로 답은 2입니다.
다른 예로 20이라는 수는 2진수 변환 시 10100이 되고 1 사이에 0이 1개이고 끝에 1로 닫히지 않기 때문에 뒤에 나오는 0 2개는 카운트 하지 않아 최대 1개입니다.
문제 풀이
저는 stack을 사용해서 반복문을 돌려 0인 경우 stack에 넣고 1이 나오면 stack의 길이를 max_zero와 비교하여 최댓값으로 바꾸고 stack을 초기화 하는 방식으로 접근하였습니다.
- 주어진 N을 2진수로 변환하는 bin 함수를 사용, 0bxxxx로 나오는 값을 문자열로 변환합니다.
- for 문을 돌리되 앞의 0b는 사용하지 않으므로 2부터 len(change) 까지 돌립니다.
- 0과 1이 나오는 경우 stack에 넣거나 초기화 + 최대 0 개수 비교를 진행합니다.
def solution(N):
# Implement your solution here
answer = 0
change = bin(N)
to_str = str(change)
stack = []
max_zero = 0
put = False
for i in range(2, len(change)):
if change[i] == '1':
max_zero = max(max_zero, len(stack))
stack = []
elif change[i] == '0':
stack.append(0)
return max_zero

'Codility' 카테고리의 다른 글
| Codility - ArrListLen (0) | 2025.06.21 |
|---|---|
| Codility - LongestPassword (0) | 2025.06.21 |