How to Solve the Binary Gap Problem in Python?

您所在的位置:网站首页 binarybin How to Solve the Binary Gap Problem in Python?

How to Solve the Binary Gap Problem in Python?

2023-03-30 07:22| 来源: 网络整理| 查看: 265

The Binary Gap Problem asks you to find the maximum distance between two 1s in the binary representation of a positive integer. Here is an example of how to solve this problem in Python:

def binary_gap(n): # convert the integer to binary binary = bin(n)[2:] # iterate through the binary string and count the gaps between 1s max_gap = 0 gap = 0 for digit in binary: if digit == '1': if gap > max_gap: max_gap = gap gap = 0 else: gap += 1 return max_gap # test the function with a sample input n = 1041 print(binary_gap(n))

In this solution, we define a function binary_gap that takes a positive integer n as input. The function first converts the integer to binary using the built-in bin function and slices off the first two characters (‘0b’) to obtain the binary string.

The function then iterates through the binary string and counts the number of zeros between two ones. If a one is encountered, the function updates the maximum gap seen so far, resets the gap counter to zero, and continues iterating. If a zero is encountered, the gap counter is incremented.

After iterating through the binary string, the function returns the maximum gap seen between two ones.

In the main part of the script, we test the function with a sample input integer n and print out the result.

To use this code with other inputs, simply replace n with the desired input integer.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3