- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count operations to remove consecutive identical bits in Python
Suppose we have a binary string s, now let us consider an operation where we select a bit and flip its value from 0 to 1 or vice-versa. We have to find the minimum number of operations needed to get a string with no three identical consecutive bits.
So, if the input is like s = "10011100", then the output will be 1, because we can flip 1 to 0 the bit at index 4 to make the string "10010100" there are no three consecutive identical bits.
To solve this, we will follow these steps −
- l := 0, count := 0
- while l < size of s, do
- r := l
- while r < size of s and s[r] is same as s[l], do
- r := r + 1
- count := count + floor of ((r - l) / 3)
- l := r
- return count
Example
Let us see the following implementation to get better understanding −
def solve(s): l = 0 count = 0 while l < len(s): r = l while r < len(s) and s[r] == s[l]: r += 1 count += (r - l) // 3 l = r return count s = "10011100" print(solve(s))
Input
"10011100"
Output
1
Advertisements
To Continue Learning Please Login
Login with Google