Codementor Events

Consecutive Binary 1's from decimal number

Published Jun 28, 2018
Consecutive Binary 1's from decimal number

Challenge

I got a challenge to write a program to find the count of binary 1's for the given decimal number.

Example

Sample Input 8
Sample Output  1

The binary representation of 8 is 1000
The maximum number of 1's is 1.

Pre-work

i usually prefer to put up the step by step before start coding. I would recommand everyone to do this on you own. Come up with your own steps.
1> Need to convert the decimal to binary
2> Get to know the number of consecutive 1's in the binary result

Approach

One of the best way to approach this use the And (&) operator and BitShift (<<) operator loop over it to get this done.
The effective of the concept is on the removing the every traling 1 for every sequence of consecutive 1s.

Snippets

while(n != 0){
            n = (n & (n << 1));
            count++;
        }

Hope it Helps! Cheers

Discover and read more posts from Hari Prasad Ranganathan
get started