>  기사  >  백엔드 개발  >  C 프로그램에서는 배열에서 가장 큰 AND 값을 갖는 요소 쌍을 인쇄합니다.

C 프로그램에서는 배열에서 가장 큰 AND 값을 갖는 요소 쌍을 인쇄합니다.

WBOY
WBOY앞으로
2023-08-29 19:41:111101검색

C 프로그램에서는 배열에서 가장 큰 AND 값을 갖는 요소 쌍을 인쇄합니다.

질문에 따르면 n개의 양의 정수를 포함하는 배열이 주어지고 배열에서 최대 AND 값을 갖는 쌍을 찾아야 합니다.

Input: arr[] = { 4, 8, 12, 16 }
Output: pair = 8 12
The maximum and value= 8

Input:arr[] = { 4, 8, 16, 2 }
Output: pair = No possible AND
The maximum and value = 0

최대 AND 값을 찾는 방법은 배열에서 최대 AND 값을 찾는 것과 유사합니다. 프로그램은 결과 AND 값을 초래하는 요소 쌍을 찾아야 합니다. 이러한 요소를 찾으려면 전체 배열을 반복하고 얻을 수 있는 최대 AND 값(결과)을 사용하여 각 요소의 AND 값을 찾으세요. arr[i] & result == result인 경우 arr[i]가 다음과 같음을 의미합니다. 생성될 최대 AND 값 AND 값의 요소입니다. 또한 최대 AND 값(결과)이 0인 경우 "불가능"을 인쇄해야 합니다.

Algorithm

int checkBit(int pattern, int arr[], int n)
START
STEP 1: DECLARE AND INITIALIZE count AS 0
STEP 2: LOOP FOR i = 0 AND i < n AND i++
   IF (pattern & arr[i]) == pattern THEN,
      INCREMENT count BY 1
STEP 3: RETURN count
STOP
int maxAND(int arr[], int n)
START
STEP 1: DECLARE AND INITIALIZE res = 0 AND count
STEP 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&rdquo;
   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 FOR
END FOR
RETURN res
STOP

Example

의 번역은 다음과 같습니다:

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 pair
int 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</p><p>");
   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("</p><p>The maximum AND value= %d ", ma);
   return 0;
}

Output

위 프로그램을 실행하면 다음과 같은 출력이 생성됩니다 −

pair = 8 9
The maximum and value= 8

위 내용은 C 프로그램에서는 배열에서 가장 큰 AND 값을 갖는 요소 쌍을 인쇄합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제