使用 C++ 中的 Bitset 統計數字二進位制表示中尾隨零的個數


給定一個整數 num 作為輸入。目標是使用 bitset 查詢 num 的二進位制表示中尾隨零的個數。

bitset 儲存其中的位 0 和 1。它是一個位數組。

例如

輸入

num = 10

輸出

Count of number of trailing zeros in Binary representation of a number using
Bitset are: 1

解釋

The number 10 in binary is represented as 1010 so trailing zeroes in it is
1.

輸入

num = 64

輸出

Count of number of trailing zeros in Binary representation of a number using Bitset are: 6

解釋

The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.

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

在這種方法中,我們使用 bitset。我們將使用 | 將 bitset 設定為 num。現在使用 for 迴圈遍歷 bitset,一旦遇到第一個 1 就中斷迴圈,否則為尾隨零遞增計數。

  • 以整數 num 作為輸入。

  • 函式 trailing_zeroes(int num) 獲取 num 並返回使用 Bitset 統計數字二進位制表示中尾隨零的個數。

  • 將初始計數設定為 0。

  • 獲取一個 bitset arr。

  • 將其設定為 num,即 arr |=num。

  • 使用 for 迴圈從 i=0 到 i<64 遍歷 arr。如果 arr[i] 為 0,則遞增計數,否則中斷迴圈。

  • 在迴圈結束時返回計數作為結果。

示例

 現場演示

#include <bits/stdc++.h>
using namespace std;
int trailing_zeroes(int num){
   int count = 0;
   bitset<64> arr;
   arr |= num;
   for (int i = 0; i < 64; i++){
      if (arr[i] == 0){
         count++;
      } else {
         break;
      }
   }
   return count;
}
int main(){
   int num = 6;
   cout<<"Count of number of trailing zeros in Binary representation of a number using Bitset are: "<<trailing_zeroes(num);
   return 0;
}

輸出

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

Count of number of trailing zeros in Binary representation of a number using Bitset are: 1

更新於: 2021 年 1 月 5 日

4K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告