Given n and k, extract the k least significant bits of n. Return -1 if k is larger than the number of bits used to represent n.
Example 1
n=11, k=211The binary representation of 11 is 1011, and we extract the 2 LSBs as 11.
Example 2
n=14, k=5-1The binary representation of 14 is 1110. Only 4 bits are used in the binary representation of 14 and the ask is for 5. Therefore, we return -1.
k characters from the result of the first step.Let’s look at the code below:
public class Main{public static void main(String[] args) {int num=8;int k=3;String binaryForm = Integer.toBinaryString(num);if(k > binaryForm.length()) System.out.println("-1");else System.out.println(binaryForm.substring(binaryForm.length() - k));}}
num.k.num to binary form using the toBinaryString() method of the Integer class.k is greater than the length of the binary string obtained in line 6, we print -1. Otherwise, we print the substring from the index of the difference of the length of the binary string and k to the end of the binary string.