HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

corejava-programming: Program to find consecutive 1 and 0 in binary equivalent

While studying decimal to binary conversion Levin felt funny seeing the occurrence of consecutive 1´s and 0´s. He asked you to help him sort out a program that will find out the number of occurrences of k consecutive 0´s or 1´s in the binary equivalent of n where k and n are user specified inputs.

Input Specifications :

First input n specifies the decimal number to be converted to binary where 0<=n<=10000 Second input k specifies the consecutive 0´s or 1´s which is supposed to occur in the binary(n)

Output Specifications :

Output contains 2 line First line contains number of occurrences of K consecutive 1´s Second line contains number of occurrences of K consecutive 0´s

Sample Input :

7 2

Sample output :



corejava x 333
programming x 150
Posted On : 2017-12-07 17:41:02.0
profile Divesh - Divesh


Here i´ll recommend to use Pattern, Matcher. It´s a bit tricky as in this problem we want to count overlapping sequences too as for input 7, binary equivalent 111 returns 2 for pattern 11.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternCounter {
public static void main(String[] args) throws Exception{
Scanner input = new Scanner(;
int n=input.nextInt();
int k=input.nextInt();
if(0<=n && n<=10000){
String binaryEquivalent = Integer.toBinaryString(n);

String zeroPattern=formPattern(k, "0");
String onePattern=formPattern(k, "1");

System.out.println(getPatternCount(onePattern, binaryEquivalent));
System.out.println(getPatternCount(zeroPattern, binaryEquivalent));
throw new IllegalAccessException("Invalid Inputs!");

public static String formPattern(int k, String sequence){
StringBuilder sb = new StringBuilder();
for(int i=0;i<k;i++)
return sb.toString();

public static int getPatternCount(String inputPattern, String inputSequence){
Pattern pattern = Pattern.compile(inputPattern);
Matcher matcher = pattern.matcher(inputSequence);
int count=0;
int pos = 0;
while (matcher.find(pos)){
pos = matcher.start() + 1;
return count;

Posted On : 2017-12-10 00:04:59
Satisfied : 1 Yes  0 No
profile Rishi Kumar - Rishi Kumar
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -