BC205 - Editorial

PROBLEM LINK:
Practice
Contest

Author: Ayush Nagal

DIFFICULTY:
MEDIUM

PREREQUISITES:
Bits, Maths

PROBLEM:
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.

EXPLANATION:
First of all, we need to convert n to binary:

int k=n;
string s="";
while(k!=0)
{
    int d=k%2;
    char t=d+'0';
    s=t+s;
    k=k/2;
}

Now we have the binary representation of n and need to count the number of consecutive 1's in it.

int l=s.length();
int c=0,ma=-1;
for(int i=0;i<l-1;i++)
{
    if(s[i]==s[i+1] && s[i]=='1')
    c++;        
    else if(s[i]=='1' && s[i+1]=='0')
    {
        c++;
        if(c>ma)
        ma=c;
        c=0;
    }
}
if(s[l-1]=='1')
c++;
if(ma==-1 || c>ma)
ma=c;

Here, ma contains the maximum number of adjacent 1's.

AUTHOR’S SOLUTION:
Author’s solution can be found here.

1 Like

I think the difficulty tag is not appropriate, we can place it in beginner tag.