Given two positive integers n and k. The problem is to check whether the bit at position k from the right in the binary representation of n is set (‘1’) or unset (‘0’).
Constraints: 1 <= k <= number of bits in the binary representation of n.
Input : n = 10, k = 2 Output : Set (10)10 = (1010)2 The 2nd bit from the right is set. Input : n = 21, k = 4 Output : Unset
Approach: Following are the steps:
- Calculate new_num = (n >> (k – 1)).
- if (new_num & 1) == 1 then bit is “Set”, else “Unset”.
Time Complexity: O(1).
- Write an Efficient Method to Check if a Number is Multiple of 3
- Position of rightmost set bit
- Check for Integer Overflow
- Find position of the only set bit
- Check if a number is multiple of 9 using bitwise operators
- Check if binary representation of a number is palindrome
- Check if a given number is sparse or not
- Cyclic Redundancy Check and Modulo-2 Division
- Check if a number is Bleak
- Check whether a given number is even or odd
- Check if a number can be expressed as a sum of consecutive numbers
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if a number has bits in alternate pattern | Set 1
- Check divisibility in a binary stream
- Efficiently check if a string has all unique characters without using any additional data structure
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Improved By : Sam007