Binary Numbers - HackerRank
Problem: https://www.hackerrank.com/challenges/30-binary-numbers
The requirement is to convert an integer and convert to a binary number format where we can get the maximum length of number of 1's.
So this is how I approached the problem:
- Convert the integer input into binary format using bin() python built-in function.
- Since we get an output type of string input for binary input, we need to slice some part of the string which is irrelevant, i.e. '0b'. In Python, we can split strings using square brackets [2:], so we remove the stop and keep the start index.
- After the string has been sliced, we can use the split() function to split based on 0 and then we can get a list of 1's separated through the 0 condition.
- After split, we need to add the lengths of each element in the list to another list so we can output the max() length of the list.
The code:
#!/bin/python3
import math
import os
import random
import re
import sys
from io import StringIO
# Binary numbers integer
sys.stdin = StringIO("""439""")
if __name__ == "__main__":
n = int(input().strip())
# We assume the value is an integer and we convert to a binary format
# Once in binary format we can get the maximum of 1's
new_n = bin(n)
# Remove the 0b
new_n = new_n[2:]
# Split based on the 0 in base-10 integer
new_n = new_n.split("0")
# Create a new list and append the lengths of the 1's
# and get the maximum
new_length = []
for x in new_n:
new_length.append(len(x))
print(max(new_length))
Problems I faced:
I faced an overall issue in converting, slicing and splitting the input data which made it difficult to prepare for getting the maximum length from the new list.