Table of Contents
Example
method 1
algorithm
Output
Home Backend Development C++ Converts the given binary string to another binary string, with minimum operands flipping all bits except one

Converts the given binary string to another binary string, with minimum operands flipping all bits except one

Sep 04, 2023 pm 11:13 PM
Convert operand binary string

Converts the given binary string to another binary string, with minimum operands flipping all bits except one

In this problem, we need to convert one binary string to another binary string by flipping the characters of the string. We can save any set bits and flip other bits, and we need to calculate the total operations to implement another string by doing this.

We can solve the problem based on the total number of "01" and "10" pairs in the given string.

Problem Statement- We are given two strings of the same length, named str1 and str2, containing "0" and "1" characters, representing binary strings. We need to convert the string str1 to str2 by doing the following.

  • We can select any set bit and flip all other bits. Flip bits means converting "0" to "1" and "1" to "0".

  • If str1 cannot be converted to str2, print -1.

Example

enter

str1 = "001001111", str2 = "011111000";
Copy after login

Output

3
Copy after login

Explanation

  • In the first operation, we keep the "1" of the second index unchanged and flip all other characters in str1. Therefore, str1 will be 111110000.

  • In the second operation, we keep the "1" at index 0 unchanged and flip all other characters. Therefore, str1 will be 100001111.

  • In the last operation, we save "1" at the 5th index. Therefore, str1 will become 011111000.

enter

 str1 = "0000", str2 = "1111";
Copy after login

Output

-1
Copy after login
Copy after login

Explanation - Cannot convert str1 to str2 because str1 does not contain any "1" character to save.

enter

 str1 = "0111", str2 = "1000";
Copy after login

Output

-1
Copy after login
Copy after login

Description - Unable to convert str1 to str2.

method 1

We can solve problems through observation. The observation is that when we hold any single set bit and perform 2 operations we can get the same string. Therefore, we need to choose a different 1 index to make changes to the string.

Also, we need to perform 2 operations to convert the 01 pair to 10. For example, leave "1" in "01". So, we get "11". After that, keep "1" at the 0th index in "11" so we get "10".

To get the answer, 01 (0 -> str1, 1 -> str2) and 10 (1 -> str1, 0 -> str2) should be the same. Otherwise, we can say that the answer does not exist.

Our main goal is to minimize the "01" and "10" pairs, since we can convert "01" to "10" in 2 operations.

algorithm

Step 1- Define the totalOperatrions() function to calculate the number of operations required to convert str1 to str2.

Step 1.2 - Initialize the count10 and count01 variables to store the "01" and "10" pairs in a string.

Step 1.3 - Loop through the strings and count pairs of 01 and 10 in both strings.

Step 1.4− If count10 and count01 are the same, return 2*count10. Otherwise, -1 is returned.

Step 2- Define the minimumOperations() function to calculate the minimum operations required to convert str1 to str2.

Step 3 - Initialize "ans" with the maximum value.

Step 4 - Call the totalOperations() function using the original string and store the result in the "operation1" variable. If the return value is not equal to -1, the minimum value from ans and operation 1 is stored in ans.

Step 5- Now we will modify the string to minimize the 01 and 10 pairs. Therefore, define stringModification() function.

Step 5.1 - In the function, we find the first pair of "1ch" in the string and pass "ch" as parameter, which can be "0" or "1". So the pair should look like 1 -> str1 and ch -> str.

Step 5.2- If the "1ch" pair is not found, return false.

Step 5.3 − If a "1ch" pair is found, keep the pair unchanged and flip the other characters of str1.

Step 6 - Execute the stringModification function to keep the "11" pair unchanged and flip the other characters. After that, the totalOperations() function is called again to find the operations required to convert str1 to str2.

Step 7− If operation 2 is not equal to -1, store the minimum value in "ans" or "1 operation 2" in "ans". Here, we added 1 because we modified the string using one operation.

Step 8 - Modify the string by leaving the first "10" pair unchanged, and calculate the operands. Again assign the minimum value to "ans".

Step 9− If "ans" is equal to INT_MAX, return −1. Otherwise, return ans.

Example

#include <bits/stdc++.h>
using namespace std;

// counting 01 and 10 pairs
int totalOperations(string str1, string str2) {
    int len = str1.size();
    int count10 = 0, count01 = 0;
    for (int p = 0; p < len; p++) {
        // If characters at p index are not same
        if (str1[p] != str2[p]) {
            // Increase count01 if 0(str1)-1(str2), else count10 if 1(str1)-0(str2)
            if (str1[p] == '0')
                count01++;
            else
                count10++;
        }
    }
    // If we have euqal number of 01 and 10 pairs, we need 2 operations to flip one pair.
    if (count01 == count10)
        return 2 * count01;
    return -1;
}
bool StringModification(string &temp1, string &temp2, char ch) {
    int len = temp1.size();
    int index = -1;
    // Find the pair of 1c character. (1 -> temp1, c -> temp2)
    for (int p = 0; p < len; p++) {
        if (temp1[p] == '1' && temp2[p] == ch) {
            index = p;
            break;
        }
    }
    // return 0 if pair is not found
    if (index == -1)
        return false;
    // Flip other characters in both strings
    for (int p = 0; p < len; p++) {
        if (p != index) {
            if (temp1[p] == '1')
                temp1[p] = '0';
            else
                temp1[p] = '1';
        }
    }
    return true;
}
// finding minimum operations
int minimumOperations(string str1, string str2) {
    int ans = INT_MAX;
    // first case with initial strings
    int operation1 = totalOperations(str1, str2);
    if (operation1 != -1)
        ans = min(ans, operation1);
    string temp1 = str1, temp2 = str2;
    // Case 2, modification for 11 pair
    if (StringModification(temp1, temp2, '1')) {
        // get operations after modification
        int operation2 = totalOperations(temp1, temp2);
        // adding 1 to operation2 as we have done one modification initially
        if (operation2 != -1)
            ans = min(ans, 1 + operation2);
    }
    // Case 3 modification for 10 pair
    temp1 = str1, temp2 = str2;
    if (StringModification(temp1, temp2, '0')) {
        int operation3 = totalOperations(temp1, temp2);
        if (operation3 != -1)
            ans = min(ans, 1 + operation3);
    }
    if (ans == INT_MAX)
        return -1;
    else
        return ans;
}
int main() {
    string str1 = "001001111";
    string str2 = "011111000";
    int ans = minimumOperations(str1, str2);
    if (ans == -1){
        cout << "S1 to S2 conversion is not possible";
    }
    else{
        cout << "Minimum number of operations required are: " << ans << "\n";
    }
    return 0;
}

Copy after login

Output

Minimum number of operations required are: 3
Copy after login

Time complexity− O(N), because we iterate over the string in stringModification() and totalOperations() functions.

Space Complexity− O(1), since we modify the same string without using any extra space.

In the code, our main purpose is to reduce the number of 01 and 10 pairs in a given string after modifying the string to minimize operations. Programmers can use various inputs and try to understand the answers.

The above is the detailed content of Converts the given binary string to another binary string, with minimum operands flipping all bits except one. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A simple guide to converting USDT ERC20 to TRC20 A simple guide to converting USDT ERC20 to TRC20 Jan 18, 2024 pm 06:09 PM

We teach you step by step how to convert USDTERC20 to TRC20 network. This is because many people like to move the USDT stablecoin from the Ethereum network to the Tron network to save on transaction fees. So, if you want to convert your ERC-20 tokens to TRC-20, I believe this tutorial will be helpful to you. The difference between ERC-20 and TRC-20 ERC-20 tokens and TRC-20 tokens represent tokens based on the Ethereum network and the Tron network respectively. There are some differences between the two networks, mainly in the following aspects: First, the Ethereum network often faces congestion and high gas fees, which may lead to transaction delays and high transaction costs. In comparison, the Tron network is relatively less congested

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

How to convert ODT to Word in Windows 11/10? How to convert ODT to Word in Windows 11/10? Feb 20, 2024 pm 12:21 PM

In this article, we will show you how to convert OpenDocumentTextDocument (ODT) files to Microsoft Word (Docx, DOC, etc.). Format. How to Convert ODT to Word in Windows 11/10 Here is how you can convert ODT documents to DOC or DOCX format on Windows PC: Convert ODT to Word using WordPad or Word The first method we are going to show you Is to use WordPad or MicrosoftWord to convert ODT to Word. Here are the steps to achieve this: First, open the WordPad app using the Start menu. Now, go to

How to convert a virtual machine to a physical machine? How to convert a virtual machine to a physical machine? Feb 19, 2024 am 11:40 AM

Converting a virtual machine (VM) to a physical machine is the process of migrating a virtual instance and associated application software to a physical hardware platform. This conversion helps optimize operating system performance and hardware resource utilization. This article aims to provide an in-depth look at how to make this conversion. How to implement migration from virtual machine to physical machine? Typically, the conversion process between a virtual machine and a physical machine is performed outside the virtual machine by third-party software. This process consists of multiple stages involving the configuration of virtual machines and the transfer of resources. Prepare the physical machine: The first step is to ensure that the physical machine meets the hardware requirements for Windows. We need to back up the data on a physical machine as the conversion process will overwrite the existing data. *Username and password for an administrator account with administrator rights to create system images. will be virtual

How to convert AI files to CDR format How to convert AI files to CDR format Feb 19, 2024 pm 04:09 PM

AI files refer to vector graphics files created by Adobe Illustrator (AI for short) software, while CDR files refer to vector graphics files created by CorelDRAW software. Since these two softwares are developed by different manufacturers, their file formats are different and cannot be directly converted to each other. However, we can convert AI files to CDR files through some methods. A commonly used conversion method will be introduced below. Step 1: Export AI files to EPS format AdobeIllust

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

Golang time processing: How to convert timestamp to string in Golang Golang time processing: How to convert timestamp to string in Golang Feb 24, 2024 pm 10:42 PM

Golang time conversion: How to convert timestamp to string In Golang, time operation is one of the very common operations. Sometimes we need to convert the timestamp into a string for easy display or storage. This article will introduce how to use Golang to convert timestamps to strings and provide specific code examples. 1. Conversion of timestamps and strings In Golang, timestamps are usually expressed in the form of integer numbers, which represent the number of seconds from January 1, 1970 to the current time. The string is

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

See all articles