Task:
Given a base- 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. When working with different bases, it is common to show the base as a subscript.
Solution:
1)Javascript:
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const n = parseInt(readLine().trim(), 10);
let binaryNumber=n.toString(2).split("");
let count=0,countArray=[],index=0;
for(let i in binaryNumber){
if(Number.parseInt(binaryNumber[i])===1)
{
count++;
}else{
countArray[index++]=count;
count=0;
}
}
if(count!==0)countArray[index]=count;
console.log(Math.max(...countArray));
}
2)Java:
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));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> myList = new ArrayList<Integer>();
int count=0;
while (n > 0) {
if(n % 2 == 1){
count++;
}else{
myList.add(count);
count=0;
}
n = n / 2;
}
if(count!=0)myList.add(count);
Collections.sort(myList);
System.out.println(myList.get(myList.size()-1));
bufferedReader.close();
}
}