Day 10: Binary Numbers HackerRank solution(30 days Code) in Java

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.

Input Format:

A single integer, n.

Constraints

  • 1 <= n <= 10^6

Output Format:

Print a single base-10 integer denoting the maximum number of consecutive 1’s in the binary representation of .

Sample Input 1:

5

Sample Output 1:

1

Sample Input 2:

13

Sample Output 2:

2

Explanation:

Sample Case 1:
The binary representation of 5  is 101 , so the maximum number of consecutive 1’s is 1.

Sample Case 2:
The binary representation of  13 is 1101 , so the maximum number of consecutive 1’s is 2.

In this question we will simply used inbuilt functionality of java i.e Integer.toBinaryString(); is used to convert any integer value into binary string.

So let’s see the solution in java:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {




    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String binary = Integer.toBinaryString(n);
        int maxZeros = 0;
        int consZero = 0;
        for(int i=0; i<binary.length(); i++) {
            char ele = binary.charAt(i);
            if(ele == '1') {
                consZero++;
                maxZeros = Math.max(maxZeros, consZero);
            }else {
                consZero = 0;
            }
        }
        System.out.println(maxZeros);

        
    }
}

Hope you guys understand the code and how to use toBinaryString(); method to convert integer to binary String in java.

So friends Thanks for reading , keep learning , happy coding..!



Categories: HackerRank Questions, JAVA

Tags: , , , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: