📌  相关文章
📜  通过一次翻转检查是否可以使所有位相同

📅  最后修改于: 2021-05-04 11:43:10             🧑  作者: Mango

给定一个二进制字符串,查找是否有可能通过恰好翻转一位来使其所有数字相等(全0或全1)。

Input: 101
Output: Yes
Explanation: In 101, the 0 can be flipped
             to make it all 1

Input: 11
Output: No
Explanation: No matter whichever digit you 
  flip, you will not get the desired string.

Input: 1
Output: Yes
Explanation: We can flip 1, to make all 0's

方法1(计数0和1)
如果字符串的所有数字可以通过执行正好一个倒装制成相同,这意味着,所述字符串具有其所有位彼此相等除了这个数字,其具有要被翻转,并且该数字必须比字符串的所有其他数字不同。该数字的值可以为零或一。因此,此字符串将具有正好等于零的一位数字,而所有其他数字均等于1,或者正好一位数字等于1,所有其他数字等于0。
因此,我们只需要检查字符串是否恰好具有等于零/一的一位数字,如果是,则答案为是;否则,答案为是。否则答案是否定的。

以下是上述想法的实现。

C++
// C++ program to check if a sinle bit can
// be flipped tp make all ones
#include 
using namespace std;
 
// This function returns true if we can
// bits same in given binary string str.
bool canMakeAllSame(string str)
{
    int zeros = 0, ones = 0;
 
    // Traverse through given string and
    // count numbers of 0's and 1's
    for (char ch : str)
        (ch == '0') ? ++zeros : ++ones;
 
    // Return true if any of the two counts
    // is 1
    return (zeros == 1 || ones == 1);
}
 
// Driver code
int main()
{
    canMakeAllSame("101") ? printf("Yes\n") : printf("No\n");
    return 0;
}


Java
// Java program to check if a single bit can
// be flipped to make all ones
public class GFG {
 
    // This function returns true if we can
    // bits same in given binary string str.
    static boolean canMakeAllSame(String str)
    {
        int zeros = 0, ones = 0;
 
        // Traverse through given string and
        // count numbers of 0's and 1's
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == '0')
                ++zeros;
            else
                ++ones;
        }
 
        // Return true if any of the two counts
        // is 1
        return (zeros == 1 || ones == 1);
    }
 
    // Driver code
    public static void main(String args[])
    {
        System.out.println(canMakeAllSame("101") ? "Yes" : "No");
    }
}
// This code is contributed by Sumit Ghosh


Python3
# python program to check if a sinle
# bit can be flipped tp make all ones
 
# This function returns true if we can
# bits same in given binary string str.
def canMakeAllSame(str):
    zeros = 0
    ones = 0
 
    # Traverse through given string and
    # count numbers of 0's and 1's
    for i in range(0, len(str)):
        ch = str[i];
        if (ch == '0'):
            zeros = zeros + 1
        else:
            ones = ones + 1
 
    # Return true if any of the two
    # counts is 1
    return (zeros == 1 or ones == 1);
 
# Driver code
if(canMakeAllSame("101")):
    print("Yes\n")
else:
    print("No\n")
 
# This code is contributed by Sam007.


C#
// C# program to check if a single bit can
// be flipped to make all ones
using System;
 
class GFG {
     
    // This function returns true if we can
    // bits same in given binary string str.
    static bool canMakeAllSame(string str)
    {
        int zeros = 0, ones = 0;
 
        // Traverse through given string and
        // count numbers of 0's and 1's
        for (int i = 0; i < str.Length; i++) {
            char ch = str[i];
            if (ch == '0')
                ++zeros;
            else
                ++ones;
        }
 
        // Return true if any of the two counts
        // is 1
        return (zeros == 1 || ones == 1);
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine(canMakeAllSame("101") ? "Yes" : "No");
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
// Check if all bits can be made same by single flip
// Idea is to add the integer value all the elements
// in the given string.
// If the sum is 1 it indicates that there is
// only single '1' in the string.
// If the sum is 0 it indicates that there is only
// single '0' in the string.
// It takes O(n) time.
 
#include 
using namespace std;
 
bool isOneFlip(string str)
{
    int sum = 0;
    int n = str.length();
 
    // Traverse through given string and
    // count the total sum of numbers
    for (int i = 0; i < n; i++)
        sum += str[i] - '0';
 
    // Return true if any of the two counts
    // is 1
    return (sum == n - 1 || sum == 1);
}
 
// Main function
int main()
{
    isOneFlip("101111111111") ? printf("Yes\n") : printf("No\n");
 
    return 0;
}


Java
/*Check if all bits can be made same by single
flip. Idea is to add the integer value all the
elements in the given string.
If the sum is 1 it indicates that there is
   only single '1' in the string.
If the sum is 0 it indicates that there is only
   single '0' in the string.
It takes O(n) time.*/
public class GFG {
 
    static boolean isOneFlip(String str)
    {
        int sum = 0;
        int n = str.length();
 
        // Traverse through given string and
        // count the total sum of numbers
        for (int i = 0; i < n; i++)
            sum += str.charAt(i) - '0';
 
        // Return true if any of the two counts
        // is 1
        return (sum == n - 1 || sum == 1);
    }
 
    // Main function
    public static void main(String args[])
    {
        System.out.println(isOneFlip("101111111111") ? "Yes" : "No");
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Check if all bits can be made same
# by single flip Idea is to add the
# integer value all the elements in
# the given string. If the sum is 1
# it indicates that there is only
# single '1' in the string. If the
# sum is 0 it indicates that there
# is only single '0' in the string.
# It takes O(n) time.
 
def isOneFlip(str):
 
    sum = 0
    n = len(str)
 
    # Traverse through given string
    # and count the total sum of
    # numbers
    for i in range( 0, n ):
        sum += int(str[i]) - int('0')
 
    # Return true if any of the two
    # counts is 1
    return (sum == n - 1 or sum == 1)
 
# Main function
(print("Yes") if isOneFlip("101111111111")
                        else print("No"))
 
# This code is contributed by Smitha


C#
/*Check if all bits can be made same by single
  flip. Idea is to add the integer value all the
  elements in the given string.
  If the sum is 1 it indicates that there is
  only single '1' in the string.
  If the sum is 0 it indicates that there is only
  single '0' in the string.
  It takes O(n) time.*/
using System;
 
class GFG {
     
    static bool isOneFlip(string str)
    {
        int sum = 0;
        int n = str.Length;
 
        // Traverse through given string and
        // count the total sum of numbers
        for (int i = 0; i < n; i++)
            sum += str[i] - '0';
 
        // Return true if any of the two counts
        // is 1
        return (sum == n - 1 || sum == 1);
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine(isOneFlip("101111111111") ? "Yes" : "No");
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


输出:

Yes

时间复杂度: O(n)其中n是字符串的长度。

方法2(计数0和1)
这个想法是计算所有位的总和。如果sum为n-1或1,则输出为true,否则为false。此解决方案不需要循环比较。

以下是上述想法的实现。

C++

// Check if all bits can be made same by single flip
// Idea is to add the integer value all the elements
// in the given string.
// If the sum is 1 it indicates that there is
// only single '1' in the string.
// If the sum is 0 it indicates that there is only
// single '0' in the string.
// It takes O(n) time.
 
#include 
using namespace std;
 
bool isOneFlip(string str)
{
    int sum = 0;
    int n = str.length();
 
    // Traverse through given string and
    // count the total sum of numbers
    for (int i = 0; i < n; i++)
        sum += str[i] - '0';
 
    // Return true if any of the two counts
    // is 1
    return (sum == n - 1 || sum == 1);
}
 
// Main function
int main()
{
    isOneFlip("101111111111") ? printf("Yes\n") : printf("No\n");
 
    return 0;
}

Java

/*Check if all bits can be made same by single
flip. Idea is to add the integer value all the
elements in the given string.
If the sum is 1 it indicates that there is
   only single '1' in the string.
If the sum is 0 it indicates that there is only
   single '0' in the string.
It takes O(n) time.*/
public class GFG {
 
    static boolean isOneFlip(String str)
    {
        int sum = 0;
        int n = str.length();
 
        // Traverse through given string and
        // count the total sum of numbers
        for (int i = 0; i < n; i++)
            sum += str.charAt(i) - '0';
 
        // Return true if any of the two counts
        // is 1
        return (sum == n - 1 || sum == 1);
    }
 
    // Main function
    public static void main(String args[])
    {
        System.out.println(isOneFlip("101111111111") ? "Yes" : "No");
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Check if all bits can be made same
# by single flip Idea is to add the
# integer value all the elements in
# the given string. If the sum is 1
# it indicates that there is only
# single '1' in the string. If the
# sum is 0 it indicates that there
# is only single '0' in the string.
# It takes O(n) time.
 
def isOneFlip(str):
 
    sum = 0
    n = len(str)
 
    # Traverse through given string
    # and count the total sum of
    # numbers
    for i in range( 0, n ):
        sum += int(str[i]) - int('0')
 
    # Return true if any of the two
    # counts is 1
    return (sum == n - 1 or sum == 1)
 
# Main function
(print("Yes") if isOneFlip("101111111111")
                        else print("No"))
 
# This code is contributed by Smitha

C#

/*Check if all bits can be made same by single
  flip. Idea is to add the integer value all the
  elements in the given string.
  If the sum is 1 it indicates that there is
  only single '1' in the string.
  If the sum is 0 it indicates that there is only
  single '0' in the string.
  It takes O(n) time.*/
using System;
 
class GFG {
     
    static bool isOneFlip(string str)
    {
        int sum = 0;
        int n = str.Length;
 
        // Traverse through given string and
        // count the total sum of numbers
        for (int i = 0; i < n; i++)
            sum += str[i] - '0';
 
        // Return true if any of the two counts
        // is 1
        return (sum == n - 1 || sum == 1);
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine(isOneFlip("101111111111") ? "Yes" : "No");
    }
}
 
// This code is contributed by Sam007

的PHP


Java脚本


输出:

Yes

感谢Sourabh Gavhale提出了此解决方案