

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 the binary representation of a number has equal number of 0s and 1s in blocks in Python
Suppose we have a number num, we have to check whether the binary representation of num has the same number of consecutive blocks of 0s and 1s. We have to keep in mind that 0 and a number with all 1s are not considered to have number of blocks of 0s and 1s.
So, if the input is like num = 455, then the output will be True, as the binary representation of this number is 111000111.
To solve this, we will follow these steps −
- bin_form := binary form of num
- one_count := a new set
- count := 1
- for i in range 0 to bit count of bin_form - 1, do
- if bin_form[i] is same as bin_form[i + 1], then
- count := count + 1
- otherwise,
- insert count into one_count
- count := 1
- if bin_form[i] is same as bin_form[i + 1], then
- if size of one_count is same as 1, then
- return True
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(num): bin_form = bin(num).replace("0b", "") one_count = set() count = 1 for i in range(len(bin_form)-1): if bin_form[i] == bin_form[i + 1]: count += 1 else: one_count.add(count) count = 1 if len(one_count) == 1: return True return False num = 455 print(solve(num))
Input
455
Output
True
- Related Questions & Answers
- Largest subarray with equal number of 0s and 1s in C++
- XOR counts of 0s and 1s in binary representation in C++
- Check if binary representation of a number is palindrome in Python
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Check if a string has m consecutive 1s or 0s in Python
- Sorting according to number of 1s in binary representation using JavaScript
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Encoding a number string into a string of 0s and 1s in JavaScript
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Check if a number has same number of set and unset bits in C++
- Golang Program to check if the binary representation of a number is palindrome or not
- Binary representation of a given number in C++
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Number of leading zeros in binary representation of a given number in C++
Advertisements