Coders Packet

Binary Gap in Python

By Sher Singh G

Python program to find the longest sequence of zeros in the binary representation of an integer.

Binary Gap in Python

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.



1. Unzip the file to any convenient location.

2. Make sure that python is installed.

3. Run the program by opening the file "".


To Run in Python Shell 

To run Python program with the python command, you need to open a command line and type in the word python, or python3 if you have both versions, followed by the path to your script, just like this:

Enter the number :529
Binary Representation of 529 is 1000010001
Binary Gap is: 4
Press return to exit


**NOTE: Binary Gap is the number of 0's between 1's in a binary number and 0's at the beginning or end of a binary number which is surrounded by 1 on one side are not considered.  


Binary Representation of 44 is 101100
Binary Gap is: 1

Download project

Reviews Report

Submitted by Sher Singh G (shersingh)

Download packets of source code on Coders Packet