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. }