Check if the given decimal number has 0 and 1 digits only 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

Live Demo

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

Updated on: 15-Jan-2021

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements