requirements

Given a positive integer n, find and return the longest distance between two adjacent 1s in the binary representation of n. If there are no two adjacent ones, return 0.

If only 0 separates two 1’s (which may not exist), they are considered adjacent to each other. The distance between two 1s is the absolute difference between their positions in their binary representation. For example, the two 1s in “1001” are 3 apart.

Example 1:

Input: n = 22 Output: 2 Description: The binary of 22 is "10110". In the binary representation of 22, there are three ones, forming two pairs of adjacent ones. In the first pair of adjacent ones, the distance between the two ones is 2. In the second pair of adjacent ones, the distance between the two ones is 1. The answer is the largest of the two distances, which is 2.Copy the code

Example 2:

Input: n = 5 Output: 2 Explanation: the binary of 5 is "101".Copy the code

Example 3:

Input: n = 6 Output: 1 Explanation: binary of 6 is "110".Copy the code

Example 4:

Input: n = 8 Output: 0 Explanation: 8 binary is "1000". There are no two 1s adjacent to each other in the binary representation of 8, so 0 is returned.Copy the code

Example 5:

Input: n = 1 Output: 0Copy the code

The core code

class Solution:
    def binaryGap(self, n: int) - >int:
        b = bin(n)[2:]
        last_one,res = 0.0
        for i,char in enumerate(b):
            if char == "1":
                res = max(res,i - last_one)
                last_one = i
        return res
Copy the code

We use the bin method to get the binary string of n, and then perform a linear scan of the string. When we encounter 1, we update the historical best distance, and finally get the maximum distance.