f=lambda n,k=1:`k`in bin(n^n/2)and-~f(n,k*10)
Try it online!
How it works
By XORing n and n/2 (dividing by 2 essentially chops off the last bit), we get a new integer m whose unset bits indicate matching adjacent bits in n.
For example, if n = 1337371, we have the following.
n = 1337371 = 101000110100000011011₂
n/2 = 668685 = 10100011010000001101₂
m = 1989654 = 111100101110000010110₂
This reduces the task to find the longest run of zeroes. Since the binary representation of a positive integer always begins with a 1, we'll try to find the longest 10* string of digits that appears in the binary representation of m. This can be done recursively.
Initialize k as 1. Every time f is executed, we first test if the decimal representation of k appears in the binary representation of m. If it does, we multiply k by 10 and call f again. If it doesn't, the code to the right of and
isn't executed and we return False.
To do this, we first compute bin(k)[3:]
. In our example, bin(k)
returns '0b111100101110000010110'
, and the 0b1
at the beginning is removed with [3:]
.
Now, the -~
before the recursive call increments False/0 once for every time f is called recursively. Once 10{j} (1 followed by j repetitions of 0) does not appear in the binary representation of k, the longest run of zeroes in k has length j - 1. Since j - 1 consecutive zeroes in k indicate j matching adjacent bits in n, the desired result is j, which is what we obtain by incrementing False/0 a total of j times.