您好,欢迎访问一九零五行业门户网

在C程序中,将一个数组中具有最大AND值的一对元素打印出来

根据问题,我们给定了一个包含n个正整数的数组,我们需要从数组中找到具有最大and值的一对。
示例input: arr[] = { 4, 8, 12, 16 }output: pair = 8 12the maximum and value= 8input:arr[] = { 4, 8, 16, 2 }output: pair = no possible andthe maximum and value = 0
寻找最大and值的方法类似于在数组中寻找最大and值。程序必须找到导致得到的and值的元素对。为了找到这些元素,只需遍历整个数组,并找到每个元素与得到的最大and值(结果)的and值,如果arr[i] & result == result,则表示arr[i]是将生成最大and值的元素。此外,在最大and值(结果)为零的情况下,我们应该打印“不可能”。
算法int checkbit(int pattern, int arr[], int n)startstep 1: declare and initialize count as 0step 2: loop for i = 0 and i < n and i++ if (pattern & arr[i]) == pattern then, increment count by 1step 3: return countstopint maxand(int arr[], int n)startstep 1: declare and initialize res = 0 and countstep 2: loop for bit = 31 and bit >= 0 and bit-- count = goto function checkbit(res | (1 << bit), arr,n) if count >= 2 then, res |= (1 << bit); end if if res == 0 print "no possible and” else print "pair with maximum and= " count = 0; loop for int i = 0 and i < n && count < 2 and i++ if (arr[i] & res) == res then, increment count by 1 print arr[i] end if end forend forreturn resstop
example的翻译为:示例#include <stdio.h>int checkbit(int pattern, int arr[], int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count;}// function for finding maximum and value pairint maxand(int arr[], int n){ int res = 0, count; for (int bit = 31; bit >= 0; bit--) { count = checkbit(res | (1 << bit), arr, n); if (count >= 2) res |= (1 << bit); } if (res == 0) //if there is no pair available printf("no possible and
"); else { //printing the pair available printf("pair with maximum and= "); count = 0; for (int i = 0; i < n && count < 2; i++) { // incremnent count value after // printing element if ((arr[i] & res) == res) { count++; printf("%d ", arr[i]); } } } return res;}int main(int argc, char const *argv[]){ int arr[] = {5, 6, 2, 8, 9, 12}; int n = sizeof(arr)/sizeof(arr[0]); int ma = maxand(arr, n); printf("
the maximum and value= %d ", ma); return 0;}
输出如果我们运行上述程序,它将生成以下输出−
pair = 8 9the maximum and value= 8
以上就是在c程序中,将一个数组中具有最大and值的一对元素打印出来的详细内容。
其它类似信息

推荐信息