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:

  1. Find an answer to an algorithmic problem,
  2. Optimize your solution for resources (computation time and space),
  3. Look for alternative data structures and algorithms to simplify your solution further,
  4. Code the solution one simple step at a time (good for practicing TDD),
  5. 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

Subscribe to SBCTricks.com

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe