문제
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:
public func solution(_ N : Int) -> Int
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].
링크
문제 분석
- 10진수를 입력받아 2진수로 변환한 뒤, 1과 1 사이의 0의 개수 binary gap을 구한다.
- 여러 개의 binary gap이 있다면 가장 큰 값을 반환한다.
- binary gap이 없다면 0을 반환한다.
ex) N = 529
2진수로 변환하면 1000010001 이다.
529는 4, 3 값을 갖는 2개의 binary gap을 갖는다. 그중 큰 4를 반환한다.
해결방안
- 10진수 -> 2진수 변환
- 2진수를 배열에 저장
- 배열의 1번 요소부터 마지막까지 순차적으로 탐색 ( 배열 0은 항상 1이기 때문에 )
- binary gap 구하기
- 0이면 zero count 변수를 1 증가
- 1이라면 이전의 binary gap과 현재 binary gap 중 큰 값을 re 변수에 저장
Solution
public func solution(_ N : Int) -> Int {
let binary = Array(String(N, radix: 2))
var zero_cnt = 0, re = 0
for i in 1..<binary.count{
if binary[i] == "0"{
zero_cnt += 1
}else{
re = max(re, zero_cnt)
zero_cnt = 0
}
}
return re
}
'📖 Coding Test > Codility' 카테고리의 다른 글
[Swift] Codility Lesson 3 - TapeEquilibrium (0) | 2022.07.23 |
---|---|
[Swift] Codility Lesson 3 - PermMissingElem (0) | 2022.07.23 |
[Swift] Codility Lesson 3 - FrogJmp (0) | 2022.07.23 |
[Swift] Codility Lesson 2 - OddOccurrencesInArray (0) | 2022.07.23 |
[Swift] Codility Lesson2 - CyclicRotation (0) | 2022.07.23 |
댓글