
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if all bits of a number are set in Python
Suppose we have a number n. We have to check whether all bits are set (1) for the given number n or not.
So, if the input is like n = 255, then the output will be True as the binary representation of 255 is 11111111.
To solve this, we will follow these steps −
- if number is same as 0, then
- return False
- while number > 0, do
- if number is even, then
- return False
- number := quotient of (number / 2)
- if number is even, then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(number): if number == 0: return False while number > 0: if (number & 1) == 0: return False number = number >> 1 return True n = 255 print(solve(n))
Input
255
Output
True
- Related Articles
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if a number has two adjacent set bits in C++
- Check if a number has same number of set and unset bits in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Check whether the number has only first and last bits set in Python
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Check if all digits of a number divide it in Python
- Prime Number of Set Bits in Binary Representation in Python
- Python program to count total set bits in all number from 1 to n.
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- Minimum number using set bits of a given number in C++
- Python Program for Check if all digits of a number divide it
- Python Count set bits in a range?

Advertisements