![]() |
VOOZH | about |
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples:
Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get only 01000 i.e 8.
We have existing solution for this problem please refer Extract ‘k’ bits from a given position in a number link. We can solve this problem quickly in python using slicing. Approach is simple,
Output:
21
Time Complexity: O(logn)
Space Complexity: O(logn)
This approach defines a function named extract_bits that takes three arguments: number, k, and p. It returns the decimal value of the k bits starting from position p (from right to left) in the binary representation of number. The function first right-shifts the number by p-1 bits to get the desired bits at the rightmost end of the number. Then, it creates a mask by left-shifting 1 by k bits and subtracting 1 to get a binary number consisting of k ones. It then bitwise-ANDs the shifted number with the mask to extract the k bits. Finally, it converts the extracted bits to a binary string and then to an integer to get the decimal value.
1. Right shift the given number by p-1 bits to get the desired bits at the rightmost end of the number.
2. Mask the rightmost k bits to get rid of any additional bits on the left.
3. Convert the resulting bits to decimal using the int() function.
21
Time Complexity: O(1)
Space Complexity: O(1)
This approach takes a decimal number num, the number of bits k, and the position of the bits p as input. It converts num to a binary string using the bin() function, removes the '0b' prefix from the string, and extracts a substring of length k starting from position p. Finally, the substring is converted back to an integer using the int() function with a base of 2.
1. Convert the decimal number to a binary string using bin().
2. Remove the '0b' prefix from the binary string.
3. Extract a substring of length k starting from position p.
4. Convert the substring back to an integer using int() with a base of 2.
5. Return the extracted integer.
21
Time complexity: O(1), The time complexity of bin() and int() is O(log n), where n is the input number, but the input num is limited to 32 bits (in most implementations of Python), so the time complexity can be considered constant.
Auxiliary Space: O(log n) The space complexity of bin() and int() is O(log n), where n is the input number, but the input num is limited to 32 bits (in most implementations of Python), so the space complexity can be considered constant.