
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 Decimal Number Has Only 0 and 1 Digits in Python
Suppose we have a number num. We have to check whether num is consists of only 0s and 1s or not.
So, if the input is like num = 101101, then the output will be True.
To solve this, we will follow these steps −
- digits_set := a new set with all elements digits of num
- delete 0 from digits_set
- delete 1 from digits_set
- if size of digits_set is same as 0, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(num): digits_set = set() while num > 0: digit = num % 10 digits_set.add(digit) num = int(num / 10) digits_set.discard(0) digits_set.discard(1) if len(digits_set) == 0: return True return False num = 101101 print(solve(num))
Input
101101
Output
True
Advertisements