
根据问题,我们给定了一个包含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 = 0 AND bit-- count = GOTO FUNCTION checkBit(res | (1 <= 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 int checkBit(int pattern, int arr[], int n){ int count = 0; for (int i = 0; i = 0; bit--) { count = checkBit(res | (1 <= 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值的一对元素打印出来的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444047.html
微信扫一扫
支付宝扫一扫