2017年2月13日 星期一

【Python】Codility in Python : Lesson 1 - Iterations【BinaryGap】

Iterations 練習題的第一題題目是【BinaryGap】
Task : Find longest sequence of zeros in binary representation of an integer.

方法一:使用 Regular Expression 的簡易方法

def solutionByRegex(N):
  return len(max(re.findall('(0*)1', bin(N)[2:]))) if N > 0 else 0

方法二:使用 strip 和 split 的簡易方法

def solutionBySplit(N):
  return len(max(bin(N)[2:].strip('0').strip('1').split('1')))

完整練習題 source code 請參閱:github

沒有留言:

張貼留言