使用 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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
解释
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
广告