Coding exercise: Binary Gap
Binary Gap is the first exercise on Codility.
Codility is used by some companies for screening job applicants.
Exercises on Codility engage you to:
- Find an answer to an algorithmic problem,
- Optimize your solution for resources (computation time and space),
- Look for alternative data structures and algorithms to simplify your solution further,
- Code the solution one simple step at a time (good for practicing TDD),
- Practice using your own favorite coding environment (although their Web application works just fine too).
We'll use PyTest with DocTest blocks to test our solution as we go.
This is the most typing-efficient way I know to do TDD in Python.
"""
>>> binaryGap(0)
0
>>> binaryGap(5)
2
"""
def binaryGap(n):
"""
https://leetcode.com/problems/binary-gap/solution/
"""
last = None
ans = 0
for i in range(32):
if (n >> i) & 1:
if last is not None:
ans = max(ans, i - last)
last = i
return ans
Test with:
$ pytest --doctest-modules binary_gap.py