Find value of k-th bit in binary representation
Given a number n and k (1 <= k <= 32), find the value of k-th bit in the binary representation of n. Bits are numbered from right (Least Significant Bit) to left (Most Significant Bit).
Input : n = 13, k = 2 Output : 0 Explanation: Binary representation of 13 is 1101. Second bit from right is 0. Input : n = 14, k = 3 Output : 1 Explanation: 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.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.