Swift 알고리즘공부 02.Binary Gap

dodiforth·2022년 6월 20일
0

코딜리티

목록 보기
2/2

난 몰랐다... Codility에는 Lessons으로 구분되는 나름 좀 더 쉬워(?)보이는 문제들 묶음도 있다는것을.
사실 지난번 Longest Password를 풀고 큰 좌절감에 살짝 빠졌었는데, 이유는 Longest Password를 풀려고 별안간 혼자 발악을 했는데 문제풀이 난이도가 Easy로 속해있어서 "아...알고리즘 문제풀이 강의를 들을까"라고 고민하던 찰나, 지난번 글에서 밝혔듯, 이 문제풀이 시리즈의 목적은 튜토리얼 지옥에서 벗어나는것이라. 그래도 힘이 닿는데 까지는 혼자서 계속 해보려고한다.

그러던중 Codility에 Lesson으로 구분된 문제들이 있었다는걸 발견해 다시(?) 시리즈를 시작한다. 오늘 문제풀이는 Binary Gap이다.

문제:

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].

바로 풀이로 넘어가 보자!

이번 문제는 지난번문제와 다르게 막 엄청 허덕이면서 버전을 여러개씩 만들면서 시도할필요 없이 금방 풀었다...

profile
일단 개발자가 되고봅시다!

0개의 댓글