Given n
and k
, extract the k
most significant bits of n
. Return -1
if k
is larger than the number of bits used to represent n
.
Example 1
The binary representation of 11
is 1011
, and we extract the 2
MSBs i.e. 10
.
Example 2
The binary representation of 14
is 1110
. Only 4 bits are used in the binary representation of 14
, and the ask is for 5
. Hence, we return -1
.
k
characters from the result of step 1public class Main{public static void main(String[] args) {int num=11;int k=2;String binaryForm = Integer.toBinaryString(num);if(k > binaryForm.length()) System.out.println("-1");else System.out.println(binaryForm.substring(0, k));}}
num
is defined.k
is defined.num
is converted to binary form.0
to the index of the difference of the length of the binary string and k is printed.