C++ 中計算範圍內的置位位元數


假設我們給定一個整數,例如 num,以及一個由左值和右值定義的範圍。任務是首先計算該數字的二進位制位,然後從左位迴圈到右位,並在給定的範圍內計算置位位元數。

二進位制數中的置位位元由 1 表示。當我們計算整數的二進位制數時,它是由 0 和 1 組成的組合。因此,在計算機術語中,數字 1 被稱為置位位元。

輸入 − int number = 50, left = 2, right = 5

輸出 − 範圍內置位位元的總數為 - 2

說明:數字 50 的二進位制表示為 110010,我們有一個從 left = 2 開始的範圍(其位元為 1)到 right = 5 結束的範圍(其位元為 1),並且在該範圍之間只有 0。因此,計數為 2。

輸入 − int number = 42, left = 3, right 4

輸出 − 範圍內置位位元的總數為 - 1

說明 − 數字 42 的二進位制表示為 101010,我們有一個從 left = 3 開始的範圍(其位元為 1)到 right = 4 結束的範圍(其位元為 0),並且在該範圍之間只有一個數字。因此,計數為 1。

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

  • 將數字輸入到整數型別的變數中,以及具有左值和右值整數的範圍。

  • 宣告一個名為 count 的變數,用於儲存無符號整數型別的置位位元總數。

  • 從 i 到 1<<7 和 i > 0 和 i 到 i / 2 開始 FOR 迴圈。

  • 在迴圈內部,檢查 num & 1 == TRUE 則列印 1,否則列印 0。

  • 啟動 while 迴圈以計算直到數字不為 0 的位元總數。

  • 在迴圈內部,設定 count = count + number & 1,並設定 number >>=1。

  • 設定一個臨時變數,例如 a,其值為 ((1 << right) - 1) ^ ((1 << (left - 1)) - 1);。

  • 此外,使用 count & a 設定 count。

  • 列印 count。

示例

 線上演示

#include<iostream>
using namespace std;
//Count total bits in a range
unsigned int bits(unsigned int number, unsigned int left, unsigned int right){
   unsigned int count = 0;
   unsigned i;
   //display the total 8-bit number
   cout<<"8-bit digits of "<<number<<" is: ";
   for (i = 1 << 7; i > 0; i = i / 2){
      (number & i)? cout<<"1": cout<<"0";
   }
   //calculate the total bits in a number
   while (number){
      count += number & 1;
      number >>= 1;
   }
   //calculate the set bit in a range
   int a = ((1 << right) - 1) ^ ((1 << (left - 1)) - 1);
   count = count & a;
   cout<<"\nCount of total set bits in a range are: "<<count;
}
int main(){
   unsigned int number = 42;
   unsigned int left = 2, right = 5;
   bits(number, left, right);
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

8-bit digits of 42 is: 00101010
Count of total set bits in a range are: 2

更新於: 2020年8月31日

284 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.