- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 the bit at given position is set or unset 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 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
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
- Related Articles
- Check whether K-th bit is set or nots in Python
- Check whether the two numbers differ at one-bit position only in Python
- 8085 program to check whether the given 16 bit number is palindrome or not
- Check whether the given number is Euclid Number or not in Python
- Check whether the given number is Wagstaff prime or not in Python
- Golang program to check if k’th bit is set for a given number or not.
- Check whether given floating point number is even or odd in Python
- Program to check whether given graph is bipartite or not in Python
- Check whether the length of given linked list is Even or Odd in Python
- Check whether the given numbers are Cousin prime or not in Python
- Check whether triangle is valid or not if sides are given in Python
- Program to check whether given matrix is Toeplitz Matrix or not in Python
- Program to check whether given number is Narcissistic number or not in Python
- Program to check whether given tree is symmetric tree or not in Python
- Python program to check whether a given string is Heterogram or not

Advertisements