POTD Solutions | 29 Oct’ 23 | Check whether K-th bit is set or not
Last Updated :
22 Nov, 2023
View all POTD Solutions
Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Bit Manipulation but will also help you build up problem-solving skills.
POTD 29 Oct Solution
POTD 29 October: Check whether K-th bit is set or not:
Given a number N and a bit number K, check if the Kth index bit of N is set or not. A bit is called set if it is 1. The position of set bit ‘1‘ should be indexed starting with 0 from the LSB side in the binary representation of the number.
Example:
Input: N = 4, K = 0
Output: No
Explanation: The binary representation of 4 is 100, in which the 0th index bit from LSB is not set. So, return false.
Input: N = 4, K = 2
Output: Yes
Explanation: Binary representation of 4 is 100, in which 2nd index bit from LSB is set. So, return true.
The idea is to use Left Shift (<<) Operator. Left shift number 1 by K to create a number that has only set bit as K-th bit and store that number in temp variable. If bitwise AND of N and temp is non-zero, then K-th bit is SET else K-th bit is NOT SET.
Follow the steps to solve the above problem:
- Create a variable temp.
- Left shift number 1 by K and store it in temp. Now temp will have only the K-th bit set.
- Perform Bitwise AND of temp and N:
- If Bitwise AND comes out to be non-zero then the K-th bit of N is set and hence return true.
- If Bitwise AND comes out to be zero then the K-th bit of N is not set and hence return false.
Below is the implementation of above approach:
C++
class Solution {
public :
bool checkKthBit( int n, int k)
{
int temp = (1 << k);
if ((n & temp) != 0)
return true ;
else
return false ;
}
};
|
Java
class CheckBit
{
static boolean checkKthBit( int n, int k)
{
int temp = ( 1 << k);
if ((n & temp) != 0 )
return true ;
else
return false ;
}
}
|
Python3
class Solution:
def checkKthBit( self , n,k):
temp = ( 1 << k)
if (n & temp) ! = 0 :
return True
else :
return False
|
Time Complexity: O(1), Left shift, right shift operator takes O(1) time.
Auxiliary Space: O(1), We are not using any extra space.
Share your thoughts in the comments
Please Login to comment...