C++ 中给定数字的二进制表示中前导零的数量
在本教程中,我们将编写一个程序来查找给定数字的二进制表示中前导零的数量。
让我们看看解决问题的步骤。
初始化数字n。
求大小为int的总位数。
找到n的二进制表示。
以二进制长度返回剩余的位。
示例
让我们看看代码。
#include输出结果using namespace std; int getLeadingZeroesCount(unsigned int n) { int totalBits = sizeof(n) * 8; string binary = ""; while (n) { int remainder = n % 2; if (remainder || binary.length() > 0) { binary += remainder; } n /= 2; } return totalBits - binary.length(); } int main() { int n = 101; cout << getLeadingZeroesCount(n) << endl; return 0; }
如果你运行上面的代码,那么你会得到下面的结果。
25
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下