In programming, it is often asked the programmers to convert a number from one specific base to another specific base. We, as humans, are easy to deal with in a Decimal Number System (base-10) but the computer machines are based on binary (base-2). Due to these base variations, we have to implement base conversions in our programs.
The given Java program takes input from the user and converts it into a binary number system. It also finds the number of consecutive ones ‘1’ in the binary form of the given number.
Check out the code:
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number"); int n = Integer.parseInt(bufferedReader.readLine().trim()); System.out.println("You entered: " + n); bufferedReader.close(); String binary = Integer.toBinaryString( n); System.out.println("Number in Binary form: " + binary); int maximumOnes = findMaximumOnes(binary); System.out.println("Maximum Consecutive '1' of " + n + " in binary form of " + binary + " = " + maximumOnes); } private static int findMaximumOnes(String binary) { int maxCount = 0; int currentCount = 0; for (int i = 0; i < binary.length(); i++) { if(binary.charAt(i) == '1') { currentCount++; maxCount = Math.max(maxCount, currentCount); } else { currentCount = 0; } } return maxCount; } }
If you face any confusion while understanding this code, just drop a query in the comment section.
Happy Coding!