📜  将二进制数组修改为所有元素的按位与为1

📅  最后修改于: 2021-04-29 09:23:03             🧑  作者: Mango

给定一个仅包含0和1的数组a []。任务是检查是否有可能对数组进行转换,以使每对索引之间的AND值均为1。唯一允许的操作是:

  • 取两个索引i和j并将a [i]和a [j]替换为a [i] | a [j]其中“ |”表示按位或运算。

如果可能,则输出为“ YES”,否则输出为“ NO”。

例子:

Input:  arr[] = {0, 1, 0, 0, 1}
Output: Yes
Choose these pair of indices (0, 1), (1, 2), (3, 4).

Input: arr[] = {0, 0, 0}
Output: No

方法:主要观察结果是,如果数组包含至少一个1,则答案为是,否则输出为NO,因为与OR等于1的结果为1,因为数组仅包含0和1。
如果至少有一个1,那么我们将选择所有值为0的索引,并用索引为1的OR值替换,并且OR值始终为1。
在所有操作之后,该数组将仅包含1,并且任何一对索引之间的AND值将为1,因为(1 AND 1)= 1。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
  
// Function to check if it is possible or not
bool check(int a[], int n)
{
    for (int i = 0; i < n; i++) 
        if (a[i]) 
            return true;
  
    return false;
}
  
// Driver code
int main()
{
  
    int a[] = { 0, 1, 0, 1 };
    int n = sizeof(a) / sizeof(a[0]);
  
    check(a, n) ? cout << "YES\n"
                : cout << "NO\n";
  
    return 0;
}


Java
// Java implementation of the above approach 
class GFG 
{
      
    // Function to check if it is possible or not 
    static boolean check(int a[], int n) 
    { 
        for (int i = 0; i < n; i++) 
            if (a[i] == 1) 
                return true; 
      
        return false; 
    } 
  
    // Driver code 
    public static void main (String[] args) 
    { 
        int a[] = { 0, 1, 0, 1 }; 
        int n = a.length; 
      
        if(check(a, n) == true ) 
            System.out.println("YES\n") ;
        else
            System.out.println("NO\n"); 
    } 
}
  
// This code is contributed by Ryuga


Python3
# Python 3 implementation of the
# above approach
  
# Function to check if it is 
# possible or not
def check(a, n):
    for i in range(n):
        if (a[i]):
            return True
  
    return False
  
# Driver code
if __name__ == '__main__':
    a = [0, 1, 0, 1]
    n = len(a)
      
    if(check(a, n)):
        print("YES")
    else:
        print("NO")
          
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the above approach 
using System;
  
class GFG 
{
      
    // Function to check if it is possible or not 
    static bool check(int []a, int n) 
    { 
        for (int i = 0; i < n; i++) 
            if (a[i] == 1) 
                return true; 
      
        return false; 
    } 
  
    // Driver code 
    public static void Main () 
    { 
        int []a = { 0, 1, 0, 1 }; 
        int n = a.Length; 
      
        if(check(a, n) == true ) 
            Console.Write("YES\n") ;
        else
            Console.Write("NO\n"); 
    } 
}
  
// This code is contributed
// by Akanksha Rai


PHP


输出:
YES