
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Whether K-th Bit is Set or Not in Python
Suppose we have a number n and another value k. We have to check whether the kth bit in n is set (1) or not. The value of k is considered from right hand side.
So, if the input is like n = 23, k = 3, then the output will be True as binary form of 23 is 10111 so the third 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 True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(n,k): temp = n >> (k - 1) if temp & 1: return True return False n = 23 k = 3 print(solve(n, k))
Input
23, 3
Output
True
Advertisements