[Leet Code] Binary Gap

Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
Input: n = 5
Output: 2
Explanation: 5 in binary is "101".
Input: n = 6
Output: 1
Explanation: 6 in binary is "110".
Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.
Input: n = 1
Output: 0
class Solution(object):
def binaryGap(self, n):
"""
:type n: int
:rtype: int
"""
binary = format(n, "b")
highest_num = 0
num_counter = 0
while num_counter < len(binary):
if binary[num_counter] == "1":
counter = 0
for i in range(num_counter+1, len(binary)):
counter += 1
if binary[i] == "1":
if counter > highest_num:
highest_num = counter
num_counter = i-1
break
num_counter += 1

return highest_num

--

--

--

Learning, and posting my findings!

Love podcasts or audiobooks? Learn on the go with our new app.

What do you need to know to work on industry-based projects(Android App Development)?

Simple and Efficient Approach for Knowledge Graph Mining from Text

Web and Mobile Backend Services Patterns

Can We Find Unused Tables In SQL Server?

Some unsolicited Old Man Advice

Getting Started with Git and Github

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!

More from Medium

DS practice

Lowest Common Ancestor of a Binary Search Tree 🐳

LeetCode 3. Longest Substring Without Repeating Characters

[Leet Code] Maximum Number of Words Found in Sentences