Extract ‘k’ most significant bits from a number
Problem Statement
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
- Input: n=11, k=2
- Output: 10
The binary representation of 11 is 1011, and we extract the 2 MSBs i.e. 10.
Example 2
- Input: n=14, k=5
- Output: -1
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.
Solution
- Convert the decimal value to binary form.
- Take the first
kcharacters from the result of step 1
Code
public 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));}}
Explanation
- Line 4:
numis defined. - Line 5:
kis defined. - Line 6:
numis converted to binary form. - Lines 7-8: If the value of k is greater than the length of the binary string obtained in line 6, we print -1. Otherwise, the substring from
0to the index of the difference of the length of the binary string and k is printed.