# 5 Best Ways to Check if a Decimal Number Contains Only 0s and 1s in Python

Rate this post

π‘ Problem Formulation: You have a decimal number, and you need to determine whether this number is comprised solely of the digits 0 and 1. For instance, if you have the input number 101101, the method should confirm it’s only composed of 0s and 1s, while a number like 1012 should be rejected since it contains a digit other than 0 or 1.

## Method 1: Using str() and set()

This method involves converting the decimal number to a string and then transforming it into a set. By definition, a set contains unique elements, so if the resulting set is either {‘0’, ‘1’} or {‘0’}, or {‘1’}, the number contains only 0s and 1s.

Here’s an example:

```number = 1011001
num_set = set(str(number))
is_binary = num_set.issubset({'0', '1'})
print(f"Does {number} have only 0's and 1's? {is_binary}")
```

Output:
Does 1011001 have only 0’s and 1’s? True

This snippet first converts the number into a string representation, then creates a set of its digits. The `.issubset()` method checks if all elements of this set are either ‘0’ or ‘1’. It’s concise and efficient but might not be the fastest for very large numbers.

## Method 2: Using Regular Expressions

Regular Expressions provide a way to match patterns in strings. In this case, we can use it to check if the string representation of the number matches a pattern where each character is either a ‘0’ or ‘1’.

Here’s an example:

```import re

number = '1011001'
is_binary = bool(re.fullmatch(r'[01]+', number))
print(f"Does {number} have only 0's and 1's? {is_binary}")
```

Output:
Does 1011001 have only 0’s and 1’s? True

This code uses the `re.fullmatch()` function to check if the entire string contains only the characters ‘0’ and ‘1’. It’s very powerful for pattern matching but may be an overkill for simple checks and is slower compared to other methods.

## Method 3: Using a Loop to Check Each Digit

By iterating over each digit in the number, you can check if every digit is either 0 or 1. This method is straightforward and doesn’t require additional libraries.

Here’s an example:

```number = 1011001
is_binary = all(digit in '01' for digit in str(number))
print(f"Does {number} have only 0's and 1's? {is_binary}")
```

Output:
Does 1011001 have only 0’s and 1’s? True

This code snippet loops through each digit of the number (converted to a string) and checks if it’s in the string ’01’. The `all()` function ensures that each digit meets the condition. It’s easy to understand and doesn’t use any complex functions or libraries.

## Method 4: Using Bitwise Operations

For a number that’s supposed to contain only 0s and 1s, we can apply bitwise operations to determine its validity. This is a low-level approach and is generally very fast.

Here’s an example:

```number = 1011001
original_number = number
is_binary = True
while number > 0:
if number & 1 not in {0, 1}:
is_binary = False
break
number >>= 1
print(f"Does {original_number} have only 0's and 1's? {is_binary}")
```

Output:
Does 1011001 have only 0’s and 1’s? True

This method checks each bit of the original number. The `& 1` operation extracts the last bit, and `>= 1` shifts the number one bit to the right. It’s very fast and efficient for numerical operations; however, it might not be as easy to understand for those unfamiliar with bitwise operations.

## Bonus One-Liner Method 5: Using int() with a Specific Base

A concise one-liner approach can be used to convert the number to its binary representation. If the conversion is successful, the number has only 0s and 1s.

Here’s an example:

```is_binary = True
try:
int(str(1011001), 2)
except ValueError:
is_binary = False
print(f"Does 1011001 have only 0's and 1's? {is_binary}")
```

Output:
Does 1011001 have only 0’s and 1’s? True

The code tries to parse the string representation of a number as a binary number (base 2). If it raises a `ValueError`, it means that the number contains digits other than 0 and 1. This is very succinct and leverages Python’s own error handling to determine the result.

## Summary/Discussion

• Method 1: Using str() and set(). Strengths: Simple and easy to implement. Weaknesses: Might be slow for very large numbers.
• Method 2: Using Regular Expressions. Strengths: Very flexible. Weaknesses: Overkill for simple checks and slower performance.
• Method 3: Using a Loop to Check Each Digit. Strengths: Straightforward and no library dependencies. Weaknesses: Might be slower for large numbers.
• Method 4: Using Bitwise Operations. Strengths: Fast and efficient. Weaknesses: Less readable for those not familiar with bitwise operations.
• Method 5: Using int() with a specific base. Strengths: Extremely concise and leverages native error handling. Weaknesses: Error handling for flow control is unconventional and may be considered a bad practice by some.