C++中具有相同設定位數的連續陣列元素的最大數量


給定一個無序的整數陣列,任務是計算兩件主要的事情:

  • 具有相同設定位數的元素
  • 並且,具有相同設定位的元素必須是連續的。

輸入

int arr[] = { 5, 8, 1, 2, 9, 12}

輸出 - 具有相同設定位數的連續陣列元素的最大數量為 - 3

解釋 - 我們將計算陣列元素的二進位制位數並計算它們的設定位數。

arr[0] = 5 => 0101 => total set bits are -: 2
arr[1] = 8 => 1000 => total set bits are -: 1
arr[2] = 1 => 0001 => total set bits are -: 1
arr[3] = 2 => 0010 => total set bits are -: 1
arr[4] = 9 => 1001 => total set bits are -: 2
Arr[5] = 12 => 1100 => total set bits are -: 2

因此,具有相同設定位數且連續的元素為 5、9 和 12。因此,具有相同設定位數的連續陣列元素的最大數量為 3

輸入 - int arr[] = { 5, 8, 1, 2}

輸出 - 具有相同設定位數的連續陣列元素的最大數量為 - 2

解釋 - 我們將計算陣列元素的二進位制位數並計算它們的設定位數。

arr[0] = 5 => 0101 => total set bits are -: 2
arr[1] = 8 => 1000 => total set bits are -: 1
arr[2] = 1 => 0001 => total set bits are -: 1
arr[3] = 2 => 0010 => total set bits are -: 1

因此,具有相同設定位數且連續的元素為 1 和 2。因此,具有相同設定位數的連續陣列元素的最大數量為 2

下面程式中使用的方法如下

  • 輸入整數型別的陣列元素

  • 使用size函式計算陣列的大小,並將其傳遞給函式

  • 取一個臨時變數並將其設定為值1,以及一個值為1的最大變數。

  • 建立一個vector型別的變數vec

  • 從0到陣列大小開始迴圈

  • 使用“__builtin_popcount(element)”函式計算陣列元素的二進位制設定位數,該函式將返回給定元素的總設定位數,並將計數儲存到向量中。

  • 從1到向量的size開始迴圈

  • 在向量中,如果vec[i+1] = vec[i],則將temp的值加1

  • 否則,將temp設定為1

  • 使用max函式選擇temp和maximum之間的最大值來設定maximum。

  • 返回最大變數

  • 列印結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//function to calculate maximum same number of bits
int maximum_SameBits(int arr[], int size){
   int temp = 1;
   int maximum = 1;
   vector<int> vec;
   for (int i = 0; i < size; i++){
      vec.push_back(__builtin_popcount(arr[i]));
   }
   for (int i = 1; i < vec.size(); i++){
      if (vec[i + 1] == vec[i]){
         temp++;
      }
      else{
         temp = 1;
      }
      maximum = max(maximum, temp);
   }
   return maximum;
}
int main(){
   int arr[] = { 5, 8, 1, 2, 9, 12};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Maximum number of contiguous array elements with same number of set bits are:
   "<<maximum_SameBits(arr, size);
   return 0;
}

輸出

Maximum number of contiguous array elements with same number of set bits are: 3

更新於:2020年8月3日

101 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.