Java Day 10: Binary Numbers




Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation.



  1. import java.io.*;
  2. import java.math.*;
  3. import java.security.*;
  4. import java.text.*;
  5. import java.util.*;
  6. import java.util.concurrent.*;
  7. import java.util.regex.*;
  8. public class Solution {
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. int n = in.nextInt();
  12. in.close();
  13. int sum = 0, max = 0;
  14. while (n > 0) {
  15. if (n % 2 == 1) {
  16. sum++;
  17. if (sum > max) {
  18. max = sum;
  19. }
  20. } else {
  21. sum = 0;
  22. }
  23. n = n / 2;
  24. }
  25. System.out.println(max);
  26. }
  27. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution


download android app

Popular HackerRank Java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube