Print ‘K’th least significant bit of a number
A number N is given. We need to print its ‘K’th Least Significant Bit.
Input : num = 10, k = 4 Output : 1 Explanation : Binary Representation of 10 is 1010. 4th LSB is 1. Input : num = 16, k = 3 Output : 0 Explanation : Binary Representation of 16 is 10000. 3rd LSB is 0.
We can easily solve this problem by following steps :
- Shift the number ‘1’ (K-1) times left.
- This will yield a number with all unset bits but the ‘K’th bit. Now, we’ll perform logical AND of the shifted number with given number.
- All bits except the ‘K’th bit will yield 0, and ‘K’th bit will depend on the number. This is because, 1 AND 1 is 1. 0 AND 1 is 0.
Time Complexity: O(1)
Auxiliary Space: O(1)
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.