【发布时间】:2018-08-03 17:32:02
【问题描述】:
我想知道我的实施是否有效。 我试图使用 python 找到该问题的最简单和低复杂度的解决方案。
def count_gap(x):
"""
Perform Find the longest sequence of zeros between ones "gap" in binary representation of an integer
Parameters
----------
x : int
input integer value
Returns
----------
max_gap : int
the maximum gap length
"""
try:
# Convert int to binary
b = "{0:b}".format(x)
# Iterate from right to lift
# Start detecting gaps after fist "one"
for i,j in enumerate(b[::-1]):
if int(j) == 1:
max_gap = max([len(i) for i in b[::-1][i:].split('1') if i])
break
except ValueError:
print("Oops! no gap found")
max_gap = 0
return max_gap
让我知道你的意见。
【问题讨论】:
-
codility BinaryGap test 允许使用 18 种不同语言编写解决方案:
C, C++, C#, Go, Java 8, Java 11, JavaScript, Kotlin, Lua, Objective-C, Pascal, PHP, Perl, Python, Ruby, Scala, Swift 4, Visual Basic。所以我认为没有任何理由将此问题仅限于 Python。
标签: python python-3.x binary