# Day 10: Binary Numbers

# Day 10: Binary Numbers

ashukumar + 67 comments check this out...

public class Solution {

`public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int rem=0,s=0,t=0; while(n>0) { rem=n%2; n=n/2; if(rem==1) { s++; if(s>=t) t=s; } else{ s=0; } } System.out.println(t); }`

}

upreti_bhawna + 3 comments Easiest code for the problem. good job!

BansheeGhoul + 7 comments how about this in java .... public class Solution {

`public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int consec1=0; String strBinary = Integer.toString(n, 2); // above is binary of given in in string String[] strparts = strBinary.split("0"); //above we get all strings of ones, below find max from them for(int i=0;i<strparts.length;i++ ){ if (consec1 < strparts[i].length()) {consec1 = strparts[i].length();} } System.out.println(consec1); //result }`

}

matonte3 + 1 comment That's probably the one that would do better in a tech interview because it actually operates on something that simulates a binary number (a string).

clint_carrion + 0 comments And then they'll ask how to make it more efficient :D

Whilst using split is nifty, it's far less efficient than just looping over the characters yourself.

duchess + 1 comment That's a great idea, I wish I had thought of it. Thanks!

trollol1365 + 1 comment i dont understand how it stops at the maximum consecutive 1

duanjing + 0 comments It does not stop, it goes through all the strings in this sring array such as 1,11,111,1,11,... from the splitting then keep the biggist length.

KrisChow + 0 comments This solution is easy to understand!

gimmick_hina + 0 comments Great!!

abhijit25k + 0 comments String strBinary = Integer.toString(n, 2); Can you please explain this line of code? How 5 is converted to 101 in binary?

almeidah + 0 comments [deleted]almeidah + 0 comments public static void main(String[] args) { int n = scanner.nextInt(); String bin[] = Integer.toBinaryString(n).split("0+"); Arrays.sort(bin); System.out.println(bin[bin.length-1].length()); scanner.close(); }

anirugu + 2 comments can you explain me how 101 is 1 and how 1101 is 2 ?

kevnolf + 5 comments 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.

anirugu + 0 comments Thanks for clerification, now I understand it.

generoustechie + 0 comments Thanks for clarification - but - it does not come out clearly in the way the question is asked.

raheezrahman + 0 comments but still how 101 has atmost 1 consecutive 1's ? ..its 0 ryt?

thakuranikesh191 + 1 comment 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:-

** Decimal rep = 2^(Max no of consecutive 1's) - 1**

baviskar_pallavi + 0 comments Not sure why your comment is not properly visible to me few of the words are cut short. Can you please explain it agait to me?

h11106298 + 0 comments [deleted]

akashkhobare14 + 0 comments [deleted]

talhaparvez285 + 0 comments CANUPLZZ EXPLAIN THE ABOVE CODE

praneethkumarre1 + 1 comment awesome job mate

VigneshSubu + 1 comment will you pls explain this??

Mtran1092 + 1 comment *rem=n%2*checks the state of the bit in the LSB (bit 0).*n=n/2*is equivalent to logical bit shift right.This code is equivalent to the use of left/right bit-shift operators in C++!

himanshusharmah1 + 1 comment Then what is the role of s and t ?

KalyanamKiran + 1 comment t holds maximum s value and s is max no of consecutive 1's. if a 0 occurs then s is reset to 0, but t has highest value of s.

if s is greater than t at anytime during loop then s is assigned to t thus preserving the maximum value of s.

steven_petrov + 0 comments Oh I understand now...the question asks for the maximum number of consecutive ones.

harrybear + 3 comments The best one.....

vshreyasi + 0 comments superb!

VigneshSubu + 0 comments Will You pls explain this ????

rcgonzalezf + 10 comments The same solution with better names:

Scanner in = new Scanner(System.in); int n = in.nextInt(); int counter = 0, max =0; while (n > 0) { int rem = n%2; if (rem==1) counter++; else counter=0; max = Math.max(counter, max); n/=2; } System.out.println(max);

RAhul_Bhatt + 1 comment What is the need of Math.max here?

jerald_fernando + 1 comment He is avoiding the use of if condition.

impex_ua + 6 comments Actually we could do the things a bit more simple here.

*Here we totally avoid branching and an extra variable:*while (n > 0) { counter = ++counter * (n%2); max = Math.max(counter, max); n/=2; }

navinxi + 2 comments - *has higher precedence than %, so make it has (n%2)

impex_ua + 0 comments yes, thanks for noticing

zuraassicpark + 0 comments what does it mean

tehwlaknigwnid + 0 comments Brilliant!

dalrawi + 1 comment I really like this solution, I'm trying to figure out why count++ does not work instead of ++count (or count = count + 1)

zykryct + 0 comments ++count increments count before it uses the value. count++ uses the value before it increments count. It can cause errors if you aren't paying attention so I usually just prefix it everytime.

amrinh + 0 comments This solution is really brilliant!

draconiac12 + 0 comments Here is my solution,

String[] binary = Integer.toBinaryString(n).split("0"); int count = 0; for(int i = 0; i < binary.length; i++){ count = binary[i].length() > count ? binary[i].length() : count; } System.out.println(count);

ajay_dayma706 + 0 comments good job bro or sister or whatever you are.

Phamacom80 + 1 comment I like your use of max here. This is called dynamic coding.

alexgiby + 0 comments thanks for the comment

sahilkumark1758 + 1 comment int main(){ int n; int max=0,count=0; cin >> n; int binary[100]; int c=0,m=0; while(n>0){ int i=1; int rem=n%2; n=n/2; if(rem==1){ count++; if(count>max) max=count; } else count=0; }

`cout<<max; return 0;`

}

adarshmr_05 + 0 comments I traced the program but still didn't understand the logic. Can you please explain?

kencluff + 0 comments Nice, I did pretty much same thing but yours is cleaner in terms of putting the max() outside the if/else. Good solution!

elvis_dukaj + 4 comments Ispired to your solution but avoiding

`if/else`

statement at all:#include <cmath> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int num; cin >> num; int counter = 0, maxCounter = 0; while (num) { const auto rem = num % 2; counter = (counter + rem) * rem; maxCounter = max(counter, maxCounter); num >>= 1; } cout << maxCounter << endl; return 0; }

ramkumarmichael + 1 comment please explain me this code....

rcgonzalezf + 2 comments 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.

irullvandalis + 1 comment If I remove max = Math.max(counter,max); I failed at testcase 2. It result 2 which is the correct answer is 3. anyone can explain me?

virus831 + 1 comment Since the counter is reset after a 0, you save the value of counter in max. otherwise you'll get wrong results. I hope it helps you understand

harrytrandesign + 0 comments So is test case 2 the only one that results in a 0 at the end? I found that without the max the only case that failed was the case for n = 439 which was test case 2.

abhishekraj29011 + 0 comments Thank you,very well explained.

robertv + 0 comments This is probably the best solution here. Good job!

Apollyon2028 + 0 comments counter = (counter + rem) * rem //this to me is beauty;.

Infinite_100p + 0 comments What is

**const**used for in this case? Isn't it normally used to declare constants (i.e., immutable literals)? But you are changing the value of rem with each iteration... I don't understand.

shivamjalkote10 + 0 comments beautiful

gorthiaishwarya + 1 comment what does this line indicate in this code n/=2

elvis_dukaj + 0 comments It means

`n = n / 2`

harrytrandesign + 1 comment Why did my solution not solve for case 3 without the max = Math.max method called here?

Any idea that would help me learn what the difference of including that check vs not including the check.

zykryct + 0 comments 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.

engineergirl636 + 0 comments OMG my mistake is just to put n greater than 2,not zero thats why test case 2 and 5 are failed ,thanks :),i understood my mistake.

prakriti_k_gand1 + 0 comments [deleted]

boleke + 5 comments What is the difference...

`char [] twoBase = Integer.toBinaryString(n).toCharArray(); int counter = 0; int max=0; for(char nums: twoBase){ if(nums =='1'){ counter++; } else{ counter=0; } if(max<counter) max = counter; } System.out.println(max);`

lampterp + 1 comment You're simply using a built-in function to calculate the binary string. Where's the fun in that? :)

j_keerthana01996 + 0 comments [deleted]robertwilk + 11 comments I would say, if you're going to that, just do:

public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[] ones = Integer.toBinaryString(n).split("[0]+"); int max = 0; for (String s : ones) { if (s.length() > max) max = s.length(); } System.out.println(max); } }

aravindputrevu + 0 comments Liked it

anisac + 1 comment Hello, I see that you used the code "for (String s : ones)". Can you please explain what this code does? Thanks

flaviarc1 + 0 comments 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.

For example:

List l = ["a", "b", "c"] for (String s : l) print (s);

Output: a b c

tanaymukund + 1 comment HI could you please explain the line String[] ones = Integer.toBinaryString(n).split("[0]+");

rishabhkapri + 0 comments It is spliting the string in terms of zero, i.e, suppose the number was 111011 the the array will be {"111","11"}

chandana204 + 0 comments Hello, I am new to programming. Can you please explain the above program. Thanks

alexgiby + 0 comments good one

alexgiby + 0 comments nice one .

shiprajain1010 + 0 comments hi can you please explain what split("[0]+") does?

shivangi28 + 0 comments That's a commendable code.

shivangi28 + 0 comments Could you explain why did you put [0]+ ? you could have just used "0" String[] ones = Integer.toBinaryString(n).split("[0]+");

janczak_marianna + 12 comments In Python 3 this would be:

n = int(input().strip()) numbers = str(bin(n)[2:]).split('0') lenghts = [len(num) for num in numbers] print(max(lenghts))

haris5 + 1 comment numbers = str("{0:b}".format(n)).split('0')

jappy2002 + 3 comments one line pythonic code:

n = int(input().strip()) print(max(len(length) for length in bin(n)[2:].split('0')))

w8vishal + 0 comments [deleted]devesh1697 + 0 comments [deleted]jagadeesh_py3 + 0 comments count = len(max(str(bin(n))[2:].split('0')))

sancuriousvaibh1 + 0 comments great piece of code.

jae_duk_seo + 0 comments very smart solution.

w8vishal + 0 comments very good logic. thumb up for you.

Dammonoit + 0 comments how about this?

len(bin(int(input()))[2:].split('0'))-1

leocoder + 1 comment Can you please explain these lines? numbers = str(bin(n)[2:]).split('0') lenghts = [len(num) for num in numbers]

Devpatat + 0 comments 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.

holmes00 + 0 comments Do you mind explaining the second line? numbers = str(bin(n)[2:]).split('0')

kishorjanwade12 + 1 comment can you tell me about this statement ,i mean how it works ...

lenghts = [len(num) for num in numbers]

Devpatat + 0 comments This are one line for loops. It basically returns a list of length of each element in number. e.g. : numbers = [11,1,11,1111,11,1] length = [2,1,2,4,2,1]

It short way to append in a list.

tomazurkiewicz + 0 comments print(len(max("{0:b}".format(int(input())).split('0'), key=len)))

ShixiangWang + 0 comments nice work.

Shi_vam11 + 1 comment can someone explain this code line by line??

Devpatat + 0 comments 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

pumacens + 0 comments Oh god, such beuty solution... i just complicate myself..

from itertools import groupby max_length = 0 groups = groupby(bin(int(input()))) for group in groups: len_num = len(list(group[1])) if group[0]=='1' and len_num > max_length: max_length = len_num print(max_length)

deepanshubendale + 1 comment whats use of max why its for ? can you give explanation of how this code is executed for string 1111101011 ?

flaviarc1 + 3 comments 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:

sum = 2, max = 0; // two consecutive 1s is sum > max? Yes it is, set max to sum and reset sum.

sum = 1, max = 2; Is sum > max? No. So max remains as 2.

sum = 5, max = 2; Is sum > max? Yes, set max to sum and reset sum.

Max is now 5 which is the largest amount of consective 1s found.

deepanshubendale + 0 comments thank you for the answer

velzend + 2 comments I was doing the following, but this failed tests >2

110011011100 = [110] +1 (0) [110] +1 [1110] +2 (00) counted 4 consecutive ones. But the answer should be 3.

I really did not get the max of consecutive 1's... Clear now, let me change the code and post it here ;)

You will get 64 bit in two tests.

My code:

int main(){

`int n, c, k, current_count, highest_count; current_count = 0; highest_count = 0; scanf("%d",&n); for (c = 63; c >= 0; c--) { k = n >> c; if (k & 1) { current_count++; // printf("1"); } else { // printf("0"); if (current_count > highest_count) highest_count = current_count; current_count = 0; } } // printf("\n"); printf("%d\n", highest_count); return 0;`

}

avtanshsahai01 + 1 comment sir what does k = n >> c; this statement do?

gvamsi244 + 0 comments Right Shifts 'n' by c times. That is for k=n>>c; // k=n/2^c;

pavn181098 + 0 comments [deleted]

salazar3593 + 1 comment It works only for default test case0. Doesnt work for all. I hava a java solution but also only works for default test case0.

bgseenivasababu + 0 comments [deleted]

deepanshubendale + 0 comments [deleted]

hsultan + 0 comments [deleted]crick_ + 0 comments Nice One! Awesome!

ryklin + 7 comments why do you need a modulus operator? you should name your variables better so that they are easier to read and understand quickly.

int main(){ int count =0; int max = 0; int n; cin >> n;

`while(n){ if (n&1){ count++; } else { count = 0; } if (max < count) max = count; n>>=1; } cout << max; return 0;`

}

Jinghua + 0 comments Beautiful solution. I love this kind of bit operation.

sxsarkar + 0 comments Awesome solution, liked it

ccarver0 + 0 comments Very nice and elegant.

elsoldollo + 2 comments // slightly modified #include <iostream> using namespace std; int main(){ int n; cin >> n; int cnt = 0, max = 0; while (n) { if (n & 1) { if (++cnt > max) max = cnt; } else cnt = 0; n >>= 1; } cout << max << endl; return 0; }

sindhuchinniah07 + 0 comments elsoldollo! Your code is cool. I can understand. But why have you written this line? if(++cnt>max)

brammi01 + 0 comments can you please explain what n >>=1 means?

shashankcuber + 1 comment 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

RA1611003010504 + 0 comments & was bitwise and here. Your method works in theory but but as seen above, this question can be solved with solutions having far lesser time complexity.

chiranjeet07 + 0 comments [deleted]madhuripatwal08 + 0 comments while(n){ if (n&1){ count++; } else { count = 0; } if (max < count) max = count; n>>=1;// explainnnn plz } cout << max; return 0; }

piyushlionhearts + 0 comments great job

eugine_s + 0 comments Did somebody hear about Java 8 features? See my solution: https://www.hackerrank.com/challenges/30-binary-numbers/forum/comments/159200

CSdisciple + 1 comment I am new to programming and would like to know why do we have the nested if statement assigning s value to t? Couldn't we just print the value of s?

lampterp + 1 comment 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

CSdisciple + 0 comments Thank you so much!

j_keerthana01996 + 0 comments [deleted]j_keerthana01996 + 0 comments [deleted]j_keerthana01996 + 0 comments [deleted]ibarry + 0 comments F*cking brilliant M8!

way2gourav91 + 1 comment your program is giving total number of ones. Its not giving highest number of consecutive ones.

lampterp + 1 comment I don't think so. Logic seems correct. s (number of ones) is reset to 0 any time a 0 is seen. Otherwise, if new number of ones (s) is greater than previous highest number (t), t is set to s.

way2gourav91 + 1 comment you can check output by running the program.

Krishna_Yadav + 1 comment 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!

vasukapil2196 + 1 comment If the problem was just to display the binary decimals like display 101(5),1101(13) etc.how to store them?

flaviarc1 + 0 comments 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:

public static String printBin (int n) { String bin = ""; while (n > 0) { bin = Integer.toString(n % 2) + bin; // store the "bits" in reverse order n /= 2; } return bin; }

tnraghu + 0 comments [deleted]VigneshSubu + 0 comments Will You Please Explain this??

VigneshSubu + 0 comments [deleted]samteck + 1 comment Good approach but can you pleas tell me whats the use of adding this line

`if(s>=t) t=s;`

rahulreddy123 + 0 comments I think for counting purpose.Because every time else block executed s value set to zero.so count value was stored in another variable t.

nitasha + 0 comments beauty :)

btmoulton + 3 comments why doesn't mine work then? Seems the same to me...

int main(){ int n,x,count,max; scanf("%d",&n); x=0; max=0; count=0; while(n){ x = n%2; n = floor(n/2); if(x==1){ count++; } else{ if(count>max){ max=count; } count=0; } } printf("%d",max); return 0; }

vanshika_bhardw1 + 0 comments [deleted]abhinav_maurya7 + 0 comments [deleted]abhinav_maurya7 + 3 comments need some modification. If you watch closely you will find the problem

int main(){ int n,max,x; max=0; int count=0; scanf("%d",&n); while(n>0) { x=n%2; n=floor(n/2); if(x==1) { count++; } else{ if(count>max) { max=count; } count=0; } } if(max>=count){ printf("%d",max); } else { printf("%d",count); } return 0; }

a_lathashree + 0 comments Brilliant

15131A1284_meera + 0 comments int main(){ int n,a[20],b[20],i=0,j=0,k=1; scanf("%d",&n); while(n<=2&&i<20) { if(n%2==0) { a[i]=0; n=n/2; } else { a[i]=1; n=(n-1)/2; } i++; } for(i=19;i>=0;i--) { b[j]=a[i]; j++; } while(j>19) { if((b[j]==1)&&(b[j]==b[j+1])) { k++; } j++; } printf("%d",k); return 0; }

can u help me with my code??

mirna_alkhoreby + 0 comments 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?

maxwell_mckinnon + 0 comments This is exactly what I did. Wondering why this wasn't in the solution.

n%2 n=n/2

Keep track of the biggest rem == 1 streak.

Great job.

praveen954kumar + 0 comments [deleted]shanavas + 2 comments Bit shift version

#include <iostream> using namespace std; int main(){ int maxOnes = 0; int ones = 0; int lastBit = 1; int n; cin >> n; while (n != 0) { if (n & lastBit) { ones++; if (ones > maxOnes) { maxOnes = ones; } } else { ones = 0; } n = n >> 1; } cout << maxOnes; return 0; }

vyom_shah98 + 0 comments In this program what "&" stands for which is in the statement if(n & lastBit)???

tejaskochar95 + 0 comments what does this line mean if (n & lastBit)

skshtripathi + 0 comments Woa!! I am still a beginner and now I am cursing my long code! Thanks alot!

yobibytes + 0 comments Try the toBinaryString function in Java. Here is a scala one-liner:

Integer.toBinaryString(n).split("0+").sorted.last.length

Ambrogio + 0 comments good job! this is simplest program.

shweta_ar + 0 comments Wow this really is the simplest one. Thanks :)

akshay_jangid05 + 0 comments superb

amit_samanta + 2 comments 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.

jybaek + 0 comments Reread the problem.

*Print a single base-10 integer denoting the maximum number of consecutive 1's in the binary representation of n.*anusha_manne + 0 comments what is test case 2 ?? Against wich value tested? any one help me

jp9573 + 0 comments Great!!

amitcode563 + 0 comments great, most simple code.

muzic_maniac7 + 0 comments Great job! But to print the correct output you need to check if(t>s) then print t, else print s.

subh_007 + 0 comments **@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.chintareddyavin1 + 2 comments But why this programm can't satisfy the test cases on numbers 439 and 65535.

dcfaber84 + 0 comments 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?

vijayanand_mit + 0 comments make sure, the max variable is printed. i had similar issue for 439

mpocatko + 0 comments you don't need to hold rem in memory, you can also replace costly % and / operations with a simple & and >> bit operations

pavithra_sri7 + 0 comments I'm new to progarmming..pls explain the code...from s++

steven_petrov + 0 comments 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.....

Is that correct?

so 101101 Would produce 4?

Forgive me if I'm dense.

Shubha_sundaram + 0 comments [deleted]sahurishabh969 + 1 comment This code will give wrong output when n=439.

vijayanand_mit + 0 comments did you print the max variable?

leoisyan + 0 comments Man this is complecate! I dont get it!

amarvadla27 + 1 comment in java style

public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String k = Integer.toBinaryString(n); char[] binary = k.toCharArray(); int count=0,max=0; for(int i=0;i<binary.length;i++){ if(binary[i]=='1') count++; if(count>max) max = count; if(binary[i]=='0') count = 0; } System.out.println(max); } }

d_michael_harris + 0 comments Thanks! This one worked the best at making me understand the solution.

koselev + 1 comment Your code inspired me for the following solution in Groovy:

int n = (new Scanner(System.in)).nextInt() int max,overAllMax = 0 while(n>0){ if(n%2==1){ max++ overAllMax = Integer.max(overAllMax, max) } else { overAllMax = Integer.max(overAllMax, max) max=0 } n=n/2 } print overAllMax

Spiznak + 0 comments Probably should only check

`overAllMax`

in the increment max branch of your`if`

tree. It doesn't need to be done for every iteration.

hshimanshu73 + 0 comments good job dude you nailed it ..!

presiyang + 0 comments [deleted]Spiznak + 0 comments You could reduce memory slightly by leaving out the declaration and assignments of

`rem`

and just use the`n%2==1`

condition in the first`if`

statment.Also, it would reduce the checks against your max if you nested that check into the increase max branch of your

`if`

tree.Minor changes, but could potentially go a long way in real world complex computations, particularly if you can eliminate this need in multiple areas.

daiict_201712052 + 0 comments M gettine error when input is 439

BansheeGhoul + 0 comments Hello this is the smallest and easiest code in java:::: public class Solution {

`public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int consec1=0; String strBinary = Integer.toString(n, 2); // System.out.println("Binary equivalent: "+Integer.toString(n, 2)); String[] strparts = strBinary.split("0"); for(int i=0;i<strparts.length;i++ ){ if (consec1 < strparts[i].length()) {consec1 = strparts[i].length();} } System.out.println(consec1); }`

}

vippayne + 0 comments [deleted]Asami + 0 comments Thank you soo much

prasannakandreg1 + 0 comments brilliantly written.

Ajay_EEE19 + 0 comments is that else loop is required??

j_wilson3355 + 0 comments If you want more performant code you should change from using modulo to being a bitwise & operator (it is faster than modulo and will do the same thing).

anupjee608 + 0 comments well done

bdiaconu + 0 comments :) I had same idea. - noticed the count for 1101 is the same as for 1011

`n = int(raw_input()) c=0 max=c while n > 0: x=n%2 n=n/2 #print x, if x == 1: c+=1 else: c=0 if c > max: max = c print max`

116cse_rec + 0 comments explain the code plz.

zuraassicpark + 0 comments timeout...

AishvaryaSivaram + 1 comment i have a doubt ! is this a recursive process or iterative ? how do mod and divide does after each operation ? it goes inside loop fpr one time only ! right

AishvaryaSivaram + 0 comments plz explain ?

aamnasharma112 + 0 comments Nice! Btw how do you think such logics? :p

punjprakash + 0 comments You dont need if(s>=t), only if (s>t) will work ( eliminating "=")

rockey20 + 0 comments Simply!! Great Code. Clean and easy. Nice thinking..!

edrouwendaal + 0 comments single line C#:

Console.WriteLine(Convert.ToString(Convert.ToInt32(Console.ReadLine()), 2).Split('0').Max(m=>m.Length));

niohack + 0 comments So simple! I just adjusted mine, thanks!

anchalesh10 + 0 comments thanks for the help buddy i thought the same logic but implemantation problem as usual to me

osama119786 + 0 comments great!

talhaparvez285 + 1 comment cann u pLZZZ EXPLAIN IT...I CANT GET IT

osama119786 + 0 comments what u didnt get, exactly?

kristalknight18 + 15 comments 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.

flame233 + 0 comments Thank you.

arnauddesombre + 1 comment The 1 liner gives the correct result, but creates a non satisfactory intermediary list:

"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:]))))parth83_rawal + 0 comments we can also use "{0:b}".format(n)

andregs + 1 comment Nice! JavaScript version:

Math.max(...Number(n).toString(2).split(/0+/).map(e => e.length))

m0026 + 2 comments nice!

can you explain this?

m0026 + 0 comments [deleted]stroncis + 1 comment 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.

thompson0005 + 0 comments trully amazing

d80b2t + 0 comments Explanation (sp.).

jianghaoyv + 0 comments nice code and good explanation. thumb up

atheis4 + 0 comments Beautiful. Love these python3 one liners!

bradywalsh + 1 comment I did mine exactly the same way in Ruby, but I think it is less confusing to read.

puts gets.strip.to_i.to_s(2).split('0').max.length

danielsinferno + 1 comment nice, you can save 2 chars using .size instead of .length ;)

canhascodez + 1 comment If we're golfing it, then:

$><<$_.to_i.to_s(2).split(?0).max.size

run with

`ruby -n`

. Using`strip`

or`chomp`

is unecessary if you're using`to_i`

. The line noise at the beginning is:$> # synonym for STDOUT << # shovel operator (appends things) $_ # first line of input

Code golf is probably bad for the brain.

arkchib + 1 comment Why are you using split(?0) instead of split('0'). This is an unfamiliar syntax for me.

canhascodez + 0 comments 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.

uthap_jhojho + 0 comments Awesome algorithm. Thanks for the share

johannesknopp + 0 comments print(len(max(re.compile("(1+)*").findall(bin(int(input()))))))

My solution

PierceofCake + 2 comments 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/python3 import sys import math n = int(input().strip()) # create an empty list to hold our binary numbers binary_list = [] # fill the list with 1s and 0s from left to right using Base-Conversion Method (remainders of dividing by 2) while True: if n > 1: if n % 2 == 0: binary_list.append(0) elif n % 2 != 0: binary_list.append(1) elif n == 1: binary_list.append(1) break elif n == 0: binary_list.append(0) break n = math.floor(n / 2) # set a counter and a max variable consec = 0 maximum = 0 # iterate through our list of 1s and 0s to find our max consecutive set of 1s for i in binary_list: if i == 1: consec += 1 if maximum <= consec: maximum = consec else: pass elif i == 0: consec = 0 print(maximum)

kanakidim + 1 comment Shorter way to get the binary list:

n = int(input().strip()) binary = [] while n > 0: remainder = n%2 binary.append(remainder) n = n//2 print(binary)

smartrahul1999k1 + 0 comments Use bin() function......

ritikaupadhyay_1 + 1 comment if maximum <= consec: maximum = consec

I was wondering if you could explain this bit to me. Kinda new to the language and quite lost.

Thank you!

robbiesoho + 0 comments 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.

vishalsuryavans1 + 0 comments thank you . awesome code with extraordinary explanation ..looking forward for such kind of code explanation thanks in advance. It will be very helpful if you tell me from where did u learn python .

suplex_city1 + 0 comments [deleted]ytian3 + 0 comments The pythonic way!

hafee_theblue + 0 comments thank you

krhimanshu1996 + 0 comments beautifully done.

prashantchikhal1 + 7 comments For those using C as programming language,

int main(){ int n; scanf("%d",&n);

`int count = 0; while (n) { n = (n & (n << 1)); count++; } printf ("%d\n", count); return 0;`

}

omagasohe + 2 comments This is pretty cleaver. Took me a minute or to to figure out why it works. For those that want to learn it's in how the & operator works

say we start out with 5869

`5869 = 1011011101101 <<1 = 0110111011010 & = 0010011001000 = 1224 <<1 = 0100110000000 & 0000010000000 = 128 <<1 = 0000100000000 & = 0000000000000 = 0`

thats 3 cycles. which is the answer. I love simple elegant solutions. too many of the newer languages have too many steps.

lampterp + 0 comments Thanks for the explanation!

Clever indeed, but intuitive no. :)

aelzeul + 0 comments I like this solution too. It is fast and actually readable. But it is not language-dependant at all. Any normal language has bitwise operations.

The same in python3:

n = int(input()) count = 0 while n: n &= n << 1 count += 1 print(count)

slachz + 0 comments That's super clever, awesome !

kasunv + 0 comments yea its wonderful way..can you tell, how to approach this kind of method??

msidargo + 0 comments THIS IS BEAUTY

riatiger + 0 comments Very good application of base binary logic operations.

sab3awy_meso + 0 comments but that isn't the maximum number of consecutive 1's in n's binary representation !!!!!!!!

kbenriquez + 0 comments Very clever solution!

ali_roustaei + 9 comments Simple way for Python3:

`print(len(max(bin(int(input().strip()))[2:].split('0'))))`

raptor985 + 3 comments Simple, but not much readable. If few lines of code, instead of one, can be more descriptive - there should be few lines. But, yes, one-liners on Python look impressive.

ali_roustaei + 0 comments You're right :)

JKDos + 1 comment This is raptor985

raptor985 cares more about writting readable code than short code.

raptor985 is smart

be more like raptor985

ali_roustaei + 0 comments You are right! :D

tejas3294 + 2 comments def func(num): return num[2:] n = int(input().strip()) a = max(func(bin(n)).split('0')).count('1') print(a)

bhattacharya_pr1 + 0 comments How does the following line work? And what is count('1') used for? a = max(func(bin(n)).split('0')).count('1')

varun_pikachu + 2 comments Using in-built function bin() followed by string processing AND max(iterable) is overkill and inefficient for this problem D:

ali_roustaei + 0 comments just for fun!

wittrup + 1 comment What efficient python solution do you suggest?

dennis_addo + 3 comments i did this in python 3 just one line

print(sorted(list(map(len,'{0:b}'.format(int(input().strip())).split("0"))),reverse=True)[0])

budnikav86 + 0 comments Wow! Great idea to split string into substring. Thanks for sharing it.

yushan + 3 comments Thank you! I did this in python 2;

import sys n = int(raw_input().strip()) print max([len(x) for x in '{0:b}'.format(n).split('0')])

babayaga321 + 0 comments can you explain the code? how does it convert the number to binary?

PS-im new to python. so many functions here!

kurian_benoy + 1 comment What is use of .format.Pls explain?

TMWP01 + 0 comments [deleted]

intelligent_fun1 + 0 comments I can't this to work, what did you do?

yeoman + 2 comments fuck off python :)

Moulick + 0 comments Come join the Python masterrace. huehuehue

tuhinbc2 + 2 comments Why? You mean that creature python, right?

thomasokonkwo91 + 0 comments Hahahahaha you are funny.

thomasokonkwo91 + 0 comments Hahahahaha you are funny.

dennis_addo + 2 comments //python 3 making it readable and less print(sorted(list(map(len,'{0:b}'.format(n).split("0"))),reverse=True)[0])

Moulick + 0 comments I find @ali_roustaei method more easier to read btw.

Please also explain yours @dennis_addo, I would love to understand it

dimm_ddr + 0 comments I think max() is better then sorted(list()). Sort is usually O(n log(n)) and can be better only in very specific cases, while max is O(n) always.

Moulick + 0 comments using format(input(), 'b') would have directly given binary without 0b.

Awesome job.

lukewrites + 1 comment Another one-liner:

`print(max(bin(n).strip('0b').split('0')).count('1'))`

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.rhymefororange + 0 comments Also, you can use len() to count ones. Since we are sure that the string only consists of ones, we can count itâ€™s length, because itâ€™s more generic.

`print len(max(bin(int(raw_input())).strip('0b').split('0')))`

henryjahja + 0 comments import sys print( len( max( bin( int( input().strip() ) )[2:].split('0') ) ) )

Haha. Also, impressive one-liner! Great job!

TMWP01 + 2 comments wow. there was another one on here that needed a list comprehension to do this. Your answer is cleaner and simpler. I did not think of this combo and did it with loops and counters:

import sys n = int(input().strip()) tst = str(bin(n)) tst = tst[2:] ones = 0 maxOnes = 0 for i in tst: if i == '1': ones += 1 if maxOnes < ones: maxOnes = ones else: ones = 0 # reset ones when 0 encountered print(maxOnes)

tmafonja1 + 0 comments brilliant!

joshisanket126 + 0 comments the ordering of the if statements must be changed.

if i =='1': ones=ones+1 else: ones=0 if maxones<ones: maxones=ones print(maxones)

ahmettortumlu25 + 0 comments Brillant!

edlaierii + 7 comments C# like most, but just transform the array to one of lengths and take max.

static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); var b = Convert.ToString(n,2); string[] arr = b.Split('0').ToArray(); int c = arr.Select(x => x.Length).Max(); Console.WriteLine(c); }

sadatshahriar + 2 comments can u please explain string[] arr = b.Split('0').ToArray(); int c = arr.Select(x => x.Length).Max(); part .

edlaierii + 0 comments 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.

salazar3593 + 1 comment Not readable. Not elegant and not a single comment. Thats why it needs explanation.

edlaierii + 2 comments 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.

salazar3593 + 0 comments Well if i dont know the language your using then maybe a comment would make me wanna be interested in reading that persons code. Just an idea im passing onon please dont bite my head off again.

broodwar1998 + 0 comments 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.

allan_registos + 0 comments The confusing line here is this:

int c = arr.Select(x => x.Length).Max();

The arr.Select needs explanation to new or non C# programmers.

j0etk + 0 comments A long but easier understand approach , perhaps ...

static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); int Quotient = n; int Remainder = 0; string BinaryValue = ""; while (Quotient > 0){ Remainder = Quotient % 2; BinaryValue = Remainder.ToString() + BinaryValue; Quotient = Quotient / 2; } Console.WriteLine (CheckConsecutive(BinaryValue)); } static string CheckConsecutive(string BinValue){ int HighestConsecutive = 0; int CurrentConsecutive = 0; for (int i = 0; i < BinValue.Length; i++){ if ( BinValue.Substring(i , 1) == "1" && i != BinValue.Length - 1){ CurrentConsecutive++; }else { if (i == BinValue.Length - 1 && BinValue.Substring(i , 1) == "1"){ CurrentConsecutive ++; } if (CurrentConsecutive > HighestConsecutive){ HighestConsecutive = CurrentConsecutive; } CurrentConsecutive = 0; } } return HighestConsecutive.ToString(); }

somdipdey + 0 comments amazing logic, mate! cheers

somdipdey + 0 comments The same logical implementation in scala but without using linq (scala doesn't have linq though) and lambda :

object Solution { def main(args: Array[String]) { val sc = new java.util.Scanner (System.in); var n = sc.nextInt(); var temp = n.toBinaryString.toInt var listOfOnes = temp.toString.split("0").toList println(listOfOnes.max.size) } }

broodwar1998 + 0 comments [deleted]starglider + 0 comments Same thing, written in a shorter way:

`static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(Convert.ToString(n,2).Split('0').Max(s=>s.Length)); }`

BinaryTrance + 1 comment 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?

lampterp + 0 comments Confusing indeed, but here "consecutive 1's" simply means a series of "one or more 1's with no 0 in between".

Hence, max. no. of consecutive 1's in 101 is said to be 1.

dzkangshu + 0 comments my solution:

n = int(input().strip()) cons_one = bin(n)[2:].split('0') print(len(max(cons_one)))

venkatesh_manoh1 + 1 comment public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.close(); int count = 0; int tempCount = 0; while (n>0){ int remainder = n%2; n= n/2; if(remainder ==1){ tempCount++; if(tempCount>count){ count = tempCount; } }else{ tempCount = 0; } } System.out.println(count); }

Ramanuja_08 + 0 comments why should we use if(tempCount>count){ count = tempCount;

coder_aky + 0 comments # 100 % working ,Simple and easy :-)

Here's in Python 3

print(len(max(bin(int(input().strip()))[2:].split('0'))))

let input :*working :***13**thenprint(bin(int(input().strip())))

*:gives:***0b1101**print(bin(int(input().strip()))[2:])

*:gives:***1101**print(bin(int(input().strip()))[2:].split('0'))

*:gives:***['11', '1']**print(max(bin(int(input().strip()))[2:].split('0')))

*:gives:***11**print(len(max(bin(int(input().strip()))[2:].split('0'))))

*:gives:***2**

adhikari_riya + 1 comment Using JavaScript we can do it fairly simply.

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

arninho + 0 comments Don't need to use the line:

var count = 0;

Sort 1170 Discussions, By:

Please Login in order to post a comment