Check whether the bit at given position is set or unset in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n and another value k. We have to check whether the kth bit in n is set (1) or unset (0). The value of k is considered from right hand side.

So, if the input is like n = 18 k = 2, then the output will be Set as binary form of 18 is 10010 so the second last bit is 1 (set).

To solve this, we will follow these steps −

  • temp := n after shifting bits (k - 1) times to the right
  • if temp AND 1 is 1, then
    • return "Set"
  • return "Unset"

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(n,k):
   temp = n >> (k - 1)
   if temp & 1:
      return "Set"
   return "Unset"

n = 18
k = 2
print(solve(n, k))

Input

18

Output

Set
raja
Published on 16-Jan-2021 04:49:46
Advertisements