# Day 10: Binary Numbers

# Day 10: Binary Numbers

ashukumar + 79 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 + 10 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 + 1 comment 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.

mela800224 + 0 comments As @clint_carrion says, I think the point here is to know how to go from decimal to binary and to be efficient traversing the string. An easy solution in C# could be the one...:

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

... but again, this goes through the string/list at least 4 times: (1) to convert from decimal to binary (2) to split it, (3) to get lengths for each string and (4) to get the max while an efficient solution uses only division, module and a loop (like the one from ashukumar)

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

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

mr_forser + 0 comments If the numbers in the string are consecutive, they will be stored together ({1, 11, 1, 111, ...}), so we only need to find the length of the longest value in the array.

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 + 3 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(); }

cokbaba + 0 comments Genius!

kushguptacse + 1 comment Arrays sort method take nlogn time. it can be done in O(N)

mqadimalusi + 0 comments public static void main(String[] args) { Scanner in = new Scanner(System.in);

`int n = in.nextInt(); long m = n; int maxCount = 0; int count = 0; long prev = -1; while(m != 0) { long current = m & 1; if(current == 1 && current == prev) { count++; }else { count = 1; } if(count > maxCount){ maxCount = count; } prev = current; m = m >> 1; } System.out.println(maxCount); in.close(); }`

rs_rickGrimes98 + 1 comment can you explain how this statement will work?

System.out.println(bin[bin.length-1].length());

chvr02091994 + 0 comments he used a sort in above step and just took the length of last string in array to get max value

Hitesh239 + 0 comments Another implementation inspired from above solution

`public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.close(); String intToBinary = Integer.toBinaryString(n); int consecutiveOne = 0; for (String str : intToBinary.split("0")) { consecutiveOne = str.length() > consecutiveOne ? str.length() : consecutiveOne; } System.out.println(consecutiveOne); }`

jacobkalas + 0 comments very neat!

mr_forser + 0 comments Really good solution, thank you.

anirugu + 3 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 + 1 comment Thanks for clerification, now I understand it.

jagatjeevannaya1 + 1 comment how 111011 is 3?

Hitesh239 + 0 comments 111011 can be divided into two groups Group1 = 111 and Group2=11 becuase the problem is ask the programmers to find the maximum number of consecutive 1's. One has to compare the 1's count in Group1 and Group2...On Comparison Group1 has more number of consecutive ones thats why answer is 3 which is count of 1's in Group1

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

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

jagatjeevannaya1 + 0 comments o means it can have maximum 1. Programme is about Maximum Consecutive of 1.

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]EC07_190040047 + 0 comments he asked for the concecutive 1's so for 5 its 1 and for 13 it is 2

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 + 5 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.icecold996 + 0 comments What does the num >>= 1; do?

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 + 12 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 + 16 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.

[deleted] + 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)

iancarter7 + 0 comments Nice work Janczak . Clever use of split.

aadityamehta15 + 1 comment Simple python3 solution for this using itertools groupby:

print(max([len(list(g)) for k, g in groupby(bin(n))]))

ARUNDIMOS + 0 comments can you explain this?

jayshilmodi999 + 0 comments What is the meaning on "[2:]" in "numbers = str(bin(n)[2:]).split('0')" ?

agaikwad2121 + 1 comment why [2:]

ac_sinha + 1 comment Its called slicing method...bin() returns binary number with '0b' prefix.

U might wanna check out videos on slicing in python. Prefer videos by Corey Schafer he is the best when it comes to teaching python.

agaikwad2121 + 0 comments Thank you i will check these videos

vaibhav24_sharma + 0 comments How its checking that ones are consecutive ????/

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 + 1 comment single line C#:

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

carlos_contreras + 0 comments AWESOME!! I knew that it can be solved with LINQ.

Congrats!

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?

ambelhadj + 0 comments Can someone please explain the dynamic between the variables s and t in this code pleae

hackzs + 0 comments good one

psmitan + 0 comments Your code is slightly wrong. For example - 23 , it's binary representation is 10111. So the maximum no. of consecutive 1's should be 3 but if you try running the code above it will give the result as 1 because it just stores the latest no. of 1's. So what you can do is : else{ t=s; s=0; } if(t

joon_online + 1 comment [deleted]mqadimalusi + 0 comments int n = in.nextInt();

`long m = n; int maxCount = 0; int count = 0; long prev = -1; while(m != 0) { long current = m & 1; if(current == 1 && current == prev) { count++; }else { count = 1; } if(count > maxCount){ maxCount = count; } prev = current; m = m >> 1; } System.out.println(maxCount); in.close();`

beingcurious07 + 0 comments Can you please explain how you approached this logic. It would be a great help!

agreesh777 + 0 comments There is an error when the test case , n = 439

ioana_popovici95 + 0 comments Your solution is really good. I would suggest even less variables, like:

public class Solution {

public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int s=0, t=0;

`while(n>0) { if(n%2==1) { s++; if(s>=t) t=s; } else{ s=0; } n/=2; } System.out.println(t); }`

}

MohammedElzanaty + 0 comments I am trying to explain what's happen behind the scence

public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); scanner.close(); // Assume n = 35 int consequenceOnes = 0; // consequenceOnes = 0 // binary of given in in string String strBinary = Integer.toString(n, 2); // strBinary: "100011" n:35 // get all strings of ones String[] strParts = strBinary.split("0"); // strParts: {"1", "", "", "11"} strBinary: "100011" // find max from One's /* * First Iteration * 1. strPart: "1" strParts: {"1", "", "", "11"} * 2. consequenceOnes = 0 strPart: "1" * 3. consequenceOnes = 1 * Second Iteration * 1. strPart: "" strParts: {"1", "", "", "11"} * 2. consequenceOnes = 0 strPart: "" * Third Iteration * 1. strPart: "" strParts: {"1", "", "", "11"} * 2. consequenceOnes = 0 strPart: "" * Last Iteration * 1. strPart: "11" strParts: {"1", "", "", "11"} * 2. consequenceOnes = 0 strPart: "11" * 3. consequenceOnes = 2 * */ for (String strPart : strParts) { // strPart: "1" strParts: {"1", "", "", "11"} if (consequenceOnes < strPart.length()) { // consequenceOnes = 0 strPart: "1" consequenceOnes = strPart.length(); // consequenceOnes = 1 } } System.out.println(consequenceOnes); }

rishi398 + 0 comments Since I was having problems in Python 3 getting all the test cases, I tried yours: remainder=0 sumVal=0 total=0 while(n>0): remainder=n%2; n=n/2; if(remainder==1): sumVal += 1 if(sumVal>=total):

total=sumVal; else: sumVal=0 print(total)`Just wouldn't work. Would appreciate some advice. Thanks in anticipation.`

abhijeet1069 + 0 comments Beautiful Logic.

shakthivanilla + 0 comments Brilliant! How did you come up with this. I was struggling to understand consecutive ones because in 5 it is 101, there is no consecutive ones right? technically? can someone please explain

faiqriwan + 0 comments Same logic but just wanted to simplify it more:

`static int calculateBinary(int n) { int temp=0; int max=0; for ( int i=0; n > 1; i++) { if (n % 2 == 1) { temp++; } else { max = Math.max(max,temp); temp = 0; } n = n / 2; } if (n ==1) temp++; max = Math.max(max,temp); return max;`

}

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

raresalm + 0 comments a shorter one :)

`n = int(input()) n2 = bin(n)[2:] n3 = {} n3 = n2.split("0") n4 = max(n3, key=len).count("1") print(n4)`

ritikaupadhyay + 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 + 8 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!

jzldruel + 0 comments It's awesome! Thanks.

ali_roustaei + 10 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?

andreziobarros + 1 comment print max([len(x) for x in bin(n).replace("0b","").split('0')])

andreziobarros + 1 comment print max([len(x) for x in bin(n).replace("0b","").split('0')])

ADAG10 + 0 comments How 'bout

`strip('0b')`

rather than`replace()`

?

TMWP01 + 0 comments [deleted]

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

Sort 1366 Discussions, By:

Please Login in order to post a comment