It's asking to print out the largest number of consecutive 1's in a binary number. 101 has at most, 1 consecutive 1's. 1101 has at most 2 consecutive 1's. The binary number 111 will have an output of 3, because there are 3 consecutive 1's. The binary number 111011, will also have an output of 3, because there are AT MOST 3 consecutive 1's.

Binary number 111 will get represented as 8 in decimal not 3 and 1101 has an output of 3 not 2, and that is the reason that 101 has an output 1 cause it has max 1 consecutive 1's. You can also relate it as:-

It reads the number, checks if it's divisible by 2 since we only have two possiblities 0 or 1, the reminder will be 1 for 1/2 and 0 for 0/2, so since we're counting the max consecutives of '1', the counter is adding itself + 1 every consecutive appeareance of '1', when 0 appears the reminder is 0, and any number * 0 = 0, so that resets the counter, at the end we only save the maxCounter and print the value of the maxCounter. I hope it helps you to understand the code.

The variable max holds the largest number of ones in a row so far. For example, if n is 11101111, after four loops max will equal 4 for the four ones that are in a row. counter will reset to 0 at the 0 in n and count up to 3 for the three ones in a row but 3 is less than 4 so after eight loops Math.max() will set max to whichever is more, max which is 4 in this example or counter which is only 3.

It is a reduced version of the for loop.
Instead of simply iterating through the list, where you'd have to later reference the index to fetch a value, this version directly iterates through the elements of the string.

First, they convert the number to binary.
As bin() returns binary numbers but with '0b' as prefix. That's why we only used [2:0].
Now we spilt our number from wherever 0 occurs.
e.g. : 1101101110 : [11,11,111]
We 'll have a list of this kind,
At last we return who has maximum length.

First, they convert the number to binary.
As bin() returns binary numbers but with '0b' as prefix.
That's why we only used [2:0].
Now we spilt our number from wherever 0 occurs.
e.g. : 1101101110 : [11,11,111]
We 'll have a list of this kind, At last we return who has maximum length

You need to keep track of the current set of consecutive ones that you are reading, as well as the maximum number ever found. Hence the comparison between max and sum.
In your example for 1111101011:
sum = 0, max = 0;
Reading from right to left you get:

i didnt get it why we used this & operator and can u please tell me the concept because i am a beginner coder.cant we do like taking out the remainders and storing it in an array . and then check the no. of consecutive one . please help

s is being used to track the current number of consecutive ones.
t is being used to track the max. number of consecutive ones.
If you simply print s, it wil change in next iteration, and you will end-up printing multiple values. We need to print the final max value.
For example: 237 ==> 11101101.
Here:
s will change in sequence: 0, 1, 0, 1, 2, 0, 1, 2, 3
t will change in sequence: 0, 1, 1, 1, 2, 2, 2, 2, 3

Nice Solution ,I tried storing the binary representation of decimal no which is not needed,we just needed to store the higher no of consecutive one's which you did perfectly while calculting the remainders!!
Great Job Bud!

Not sure what your questions is, but are you just asking how to display binary numbers? Also be careful, there isn't a thing called binary decimals, they're both different bases (base 2 and base 10).
Anyhoo, the binary numbers are the actual representation of numbers, so they're naturally stored as binary. If you want to print them out then the easiest way is to use a string, like so:

can any one explain this code please, I think I'm lost in all these conditional statements, why do I need to check if count is greater than maximum twice?! why maxCounter change its value many times? is that thing deals with the compiler and dynamic memory allocation?

Please, let me know how you were able to pass the Test Case# 2. I am trying to submit the code, it gives a message the test case 2 failed. I check the Expected Input and Output of the Test Case, they are incorrect, means, expected output value is incorrect.

@ashukumar, Suppose if you just don't have to count the contiguous numbers instead you have to make an method which takes int as input and then returns binary to the input, and somewhere it should also print the trailing occurence of 0s or 1s.

In cases where the final continuous series of 1's was the longest (or the binary representation is all 1's) do you have a final check after your loop and before printing which is larger, max or the length of the current sequence?

I'm having trouble understanding why this work. For example, let's use the number 65. It's greater than 0 so the while loop starts.

rem = 1
n = 32

And then the if statement executes. And because S goes up from 0 to 1, t becomes 1.

But the second time around 32 is divided evenly and REM = 0. Doesn't this mean that the else statement executes and s = 0. So every time there is a 1 it gets stored in T. If there are two 1's then 2 increments by 2.....

Python3: for those that don't understand the one liner
print(len(max(bin(int(input().strip()))[2:].split('0'))))

for sake of explenation im going to replace input() with '13' and break the code down.

1- int(input().strip()) ==> int('13'.strip()) takes the input of the number and strips any spaces on either side, then converts it from a string to an interger. the result is the interger 13.

2- bin(13)[2:].split('0') ==> the bin() method takes a number and converts it to binary. in this case when you enter bin(13) it returns '0b1101'. the [2:] allows us to omit the '0b' at the beginning of the string. which leaves us with '1101'.split('0').
This string method takes '1101' and splits it into a list. We end up with ['11','1'].

3-len(max(['11','1'])) ==> the max() method is simply going to look for the biggest value. In this case the biggest one is '11'. '11' is passed to the len() method which just returns the length of the object in it. In this case the object is the string '11' which has two characters, so len('11') returns 2. Which in turn is also the longest consecutive amount of ones.

"11001".split('0') returns ['11', '', '1']
However, the desired list is the list of all 1s and should be ['11', '1']

we need to split with 1 or more consecutive 0s:
re.split("0+", "11001") returns ['11', '1']
which is a better list (you could use it to answer questions like: how many blocs of consecutive 1s are there in the binary representation?)

the one liner becomes:
print(len(max(re.split("0+",bin(int(input().strip()))[2:]))))

Good answer, but uses spread/rest operator "..." and arrow function "=>", which are supported just from ES6, so this solution have less compatibility without shims. If you want to better understand, how it works, dissect to chained elements:
Math.max(
...
.Number(input)
.toString(2)
.split(/0+/)
.map(e => e.length)
)

The main idea here is (how i understand, please correct me if wrong):

First to convert input to number, but in case you are sure input is number, no need for Number().

Then toString() with parameter "2", which outputs representation in binary.

Then split output with regex to groups of ones.

Then with map() method creating new array with lengths of ones. This map prototype have less compatibility too.

Finally Math.max is wrapping all this and returns highest number from final array.

Now all the "looping" is done by spread operator and arrow function, which are new in Javascript, they are the main "secret" ingredient here.

The unary ? operator produces a single character string in Ruby 1.9 and above. In previous versions it would produce the ASCII value for a character, so ?d #=> 100. Frankly it's an obscure bit of syntax that has no purpose beyond code golf.

Thank you for this explanation. I'm new to programming and still struggle with coming up with short and simple solutions like this. Now I know there's a method for converting numbers to binary in Python!

My solution is embarrassingly long at 41 lines of code, may not be "Pythonic" or elegant, and may even be considered brute force, but it seems to have passed all of the test cases. I know that Python has a lot of extremely useful things already built into it, but as a beginner, I'm finding it more useful to break down the problem and figure out how to get from A to B using what I already know.

Then, once I've come up with my own solution (inefficient though it may be), I take a look at what others have done and end up discovering new and powerful ways to do things in Python. It's one of my favorite things so far about learning how to program.

If anyone has any advice on how to clean up my code or make it more efficient, I'm all ears. I'm sure I won't be able to produce any of these amazing one-liners anytime soon, but I hope to get there someday.

#!/bin/python3importsysimportmathn=int(input().strip())# create an empty list to hold our binary numbersbinary_list=[]# fill the list with 1s and 0s from left to right using Base-Conversion Method (remainders of dividing by 2)whileTrue:ifn>1:ifn%2==0:binary_list.append(0)elifn%2!=0:binary_list.append(1)elifn==1:binary_list.append(1)breakelifn==0:binary_list.append(0)breakn=math.floor(n/2)# set a counter and a max variableconsec=0maximum=0# iterate through our list of 1s and 0s to find our max consecutive set of 1sforiinbinary_list:ifi==1:consec+=1ifmaximum<=consec:maximum=consecelse:passelifi==0:consec=0print(maximum)

For every '1', 1 gets added to consec, which counts our consecutive 1's. When maximum is less than consec, maximum takes on consec's value. When the function encounters a zero, consec goes back to nil but maximum keeps it's value. Maximum changes value everytime it is less than consec.

Not very readable, but:
Use bin(n) to turn it into binary, strip('0b') from the front, split the number at each 0, leaving you with just strings of 1's.
Take the max (biggest) string of 1's, and then count how many 1's are in that string.

my comment wasn't enough to explain? The split separates all the numbers, discarding the 0s. there using the Select method, which transforms, to create a list of ints based on length. finally taking the max of those numbers.

First off if you need comments for what each line does you need to go back to programming 101, because you have no clue what anything is doing. Comments are for keeping track of processes you are doing within a program so someone coming in after you knows what it is the lines are of code are there for.
The only reason I post my solutions is for others to compare their "working" solutions, or figure out why their solution is failing.

I code in C# so I fully understand this. Other languages unfortunately do not get the luxury of LINQ. I started with Python 3 and laded my journey with C# recently (2 years ago). Others may imply things differently, we cannot discriminate between views here. If they are new and do not understand coding, it is still helpful in their learning process to have been explained why something was done this way. In most languages you would have to do the logic yourself where as luckily in C# we've been given libraries to assist in this. Please be kind even when you feel others don't deserve it, not for them, but as a relection of yourself.

Unfortunately, I don't understand the meaning of "consecutive 1s". Doesn't consecutive 1s mean occurence of a 1 right after another 1? for example, If the number is 101, shouldn't the number of consecutive 1s be 0 since there are only two ones and they are separated by a 0?

functionmain(){varn=parseInt(readLine());varcount=0;// to give an array of 1svarBinArr=n.toString(2).split('0');// if you are not using ES6 the you can also do this// var max = Math.max.apply(null, BinArr)varmax=Math.max(...BinArr);console.log(max.toString().length);}