Day 10: Binary Numbers | 30 Days Of Code | HackerRank Solution

Hello coders, today we are going to solve Day 10: Binary Number HackerRank Solution in C++, Java and Python.

Day 10: Binary Numbers

Objective

Today, we’re working with binary numbers.

Task

Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1‘s in n‘s binary representation. When working with different bases, it is common to show the base as a subscript.

Example

n = 125

The binary representation of 12510 is 11111012. In base 10, there are 5 and 1 consecutive ones in two groups. Print the maximum, 5.

Input Format

A single integer, n.

Constraints

  • 1 <= n <= 106

Output Format

Print a single base-10 integer that denotes the maximum number of consecutive 1‘s in the binary representation of n.

Sample Input 1

5

Sample Output 1

1

Sample Input 2

13

Sample Output 2

2

Explanation

Sample Case 1:
The binary representation of 510 is 1012, so the maximum number of consecutive 1‘s is 1.

Sample Case 2:
The binary representation of 1310 is 11012, so the maximum number of consecutive 1‘s is 2.

Solution – Day 10: Binary Numbers

C++

#include <iostream>
using namespace std;

int main() {

    int n;
    cin >> n;

    int sum = 0;
    int max = 0;

    while (n > 0) {
        if (n % 2 == 1) {
            sum++;
            if (sum > max) max = sum;
        } else sum = 0;
        n = n / 2;
    }
    cout << max;
    return 0;
}

Java

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        // convert to binary and split into strings of consecutive ones
        String[] groupings = Integer.toBinaryString(n).split("0");
        int max = 0;
        for(String s : groupings){
            if(max < s.length()){
                max = s.length();
            }
        }
        System.out.println(max);
    }
}

Python

num = int(input())

result = 0
maximum = 0

while num > 0:
    if num % 2 == 1:
        result += 1
        if result > maximum:
            maximum = result

    else:
        result = 0

    num //= 2

print(maximum)

Disclaimer: The above Problem (Day 10: Binary Numbers) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *