Convert decimal to binary number, then count the consecutive 1's in the binary number.
Convert decimal to binary number, then count the consecutive 1's in the binary number.
Input: 63
Output: 6
Explanation: 63 decimal format
binary format for 63 is 111111, so there are 6 consecutive 1's in the binary number.
another example: If input is 13, binary format is 1101, so the output is 2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class HackerRank { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int input=0; | |
int count=0,x=0,i=1,k=0; | |
input=Integer.parseInt(in.nextLine().trim()); | |
String binary=Integer.toBinaryString(input); | |
int [] arr=new int[binary.length()]; | |
do{ | |
if(String.valueOf(binary.substring(x,i)).contains("1")){ | |
count++; | |
}else { | |
i=x+1; | |
arr[k]=count; //saving consecutive counts of 1 in an array. | |
count=0; //resetting the value of counter | |
k++; | |
} | |
x=i; | |
i++; | |
}while(i<=binary.length()); | |
if(k<1){ | |
arr[0]=count; | |
System.out.println(arr[0]); | |
} | |
else{ | |
arr[k]=count; //adds the last consecutive 1's count after the zero. | |
int max=arr[0]; //to print the maximum value of array. | |
for(int f=0;f<arr.length;f++){ | |
if(arr[f]>max) | |
max=arr[f]; | |
} | |
System.out.println(max); | |
in.close(); | |
} | |
} | |
} |
Input: 63
Output: 6
Explanation: 63 decimal format
binary format for 63 is 111111, so there are 6 consecutive 1's in the binary number.
another example: If input is 13, binary format is 1101, so the output is 2.
another example : input 439
output is 3.
Since binary format is 110110111. 3 consecutive 1's are found to be highest in it.
output is 3.
Since binary format is 110110111. 3 consecutive 1's are found to be highest in it.
next example: input 65535
output is 16.
since binary format is 1111111111111111. 16 consecutive 1's are found to be highest in it.
output is 16.
since binary format is 1111111111111111. 16 consecutive 1's are found to be highest in it.
Comments
Post a Comment