Counting the number of 1 bits in a sorted bit array
I agree with your assessment of the code being unnecessarily long and awkward. It looks like the root cause is an opportunistic optimization.

The bad news is that most of the secondary tests (like arr[mid - 1] == 0 and arr[mid - 1] == 1) are bound to fail, so not only they contribute to awkwardness of the code - they also hurt the performance (by about a factor of 2, if I am not mistaken).

I recommend to keep it simple, and test only what is necessary:

    l, r = 0, len(arr)
    while l &lt; r:
        mid = l + (r - l) // 2
        if arr[mid] == 1:
            r = mid
        else:
            l = mid + 1
    return len(arr) - l


Notice that working on a semi-open range (that is, mid is beyond the range) also makes it cleaner.