[codility] BinaryGap with Python
문제
https://app.codility.com/programmers/lessons/1-iterations/binary_gap/
BinaryGap coding task - Learn to Code - Codility
Find longest sequence of zeros in binary representation of an integer.
app.codility.com
풀이
정수 N을 이진법으로 표현했을 때 연속되는 0의 최대 시퀀스를 구하는 문제이다.
먼저, 정수 N을 이진법으로 표현하기 위해 format() 함수를 사용했다. format() 함수 사용법은 아래 링크에서 확인이 가능하다. 간단하게 설명하자면 format(value, format_spec) 형식으로 사용할 수 있고. format(N, 'b') 는 N을 b(Binary format)으로 변환한다는 의미이다.
https://docs.python.org/3/library/functions.html#format
Built-in Functions — Python 3.10.4 documentation
Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer, a floating poin
docs.python.org
https://docs.python.org/3/library/string.html#formatspec
string — Common string operations — Python 3.10.4 documentation
string — Common string operations Source code: Lib/string.py String constants The constants defined in this module are: string.ascii_letters The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-
docs.python.org
답
def solution(N):
binary = format(N, 'b')
m_count = 0
count = 0
for i in binary:
if i == '1':
if m_count < count :
m_count = count
count = 0
else :
count += 1
return m_count