
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 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
Advertisements