Given a number n and k (1 <= k <= 32), find value of k-th bit in binary representation of n. Bits are numbered from right (Least Significant Bit) to left (Most Significant Bit).
Input : n = 13, k = 2 Output : 0 Binary representation of 13 is 1101. Second bit from right is 0. Input : n = 14, k = 3 Output : 1 Binary representation of 14 is 1110. Third bit from right is 1.
1) Find a number with all 0s except k-th position. We get this number using ( 1 << (k-1) ). For example if k = 3, then ( 1 << 2) gives us (00..00100).
2) Do bitwise and of above obtained number with n to find if k-th bit in n is set or not.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find the n-th number whose binary representation is a palindrome
- Find longest sequence of 1's in binary representation with one flip
- Find consecutive 1s of length >= n in binary representation of a number
- Find the number obtained after concatenation of binary representation of M and N
- Binary representation of a given number
- Maximum 0's between two immediate 1's in binary representation
- XOR counts of 0s and 1s in binary representation
- Next greater number than N with exactly one bit different in binary representation of N
- Largest number with binary representation is m 1's and m-1 0's
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Maximum distance between two 1's in Binary representation of N
- Binary representation of previous number
- 1 to n bit numbers with no consecutive 1s in binary representation
- Prime Number of Set Bits in Binary Representation | Set 1
- Length of the Longest Consecutive 1s in Binary Representation
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.