📜  数组所有元素的按位与

📅  最后修改于: 2021-09-07 02:27:29             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是找出数组所有元素的按位AND(&)

例子:

方法:思路是遍历所有数组元素对所有元素进行按位运算打印得到的结果。

下面是上述方法的实现:

C++14
// C++ program to find bitwise AND
// of all the elements in the array
#include 
using namespace std;
  
int find_and(int arr[], int len){
          
    // Initialise ans variable is arr[0]
    int ans = arr[0];
  
    // Traverse the array compute AND
    for (int i = 0; i < len; i++){
        ans = (ans&arr[i]);
    }
    // Return ans
    return ans;
}
 
// Driver function
int main()
{
    int arr[] = {1, 3, 5, 9, 11};
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call to find AND
    cout << find_and(arr, n);
    return 0;
}
 
// This code is contributed by sapnasingh4991


Java
// Java program to find bitwise AND
// of all the elements in the array
import java.util.*;
class GFG{
// Function to calculate bitwise AND
    static int find_and(int arr[]){
         
        // Initialise ans variable is arr[0]
        int ans = arr[0];
         
        // Traverse the array compute AND
        for (int i=0;i


Python3
# Python program to find bitwise AND
# of all the elements in the array
 
# Function to calculate bitwise AND
def find_and(arr):
     
    # Initialise ans variable is arr[0]
    ans = arr[0]
     
    # Traverse the array compute AND
    for i in range(1, len(arr)):
        ans = ans&arr[i]
         
    # Return ans
    return ans
     
# Driver Code
if __name__ == '__main__':
    arr = [1, 3, 5, 9, 11]
     
    # Function Call to find AND
    print(find_and(arr))


C#
// C# program to find bitwise AND
// of all the elements in the array
using System;
class GFG{
// Function to calculate bitwise AND
    static int find_and(int[] arr){
         
        // Initialise ans variable is arr[0]
        int ans = arr[0];
         
        // Traverse the array compute AND
        for (int i=0;i


Javascript


输出:
1

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live