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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
2 修祖屋祝福语简短
9 带清的简短祝福语
10 法考面试祝福语简短
11 对航母的祝福语简短
12 生日祝福语 简短独特高考
13 同事男生节祝福语简短
14 六十岁大寿祝福语简短
15 写给男生简短的祝福语
16 新年简短的祝福语爱情
17 祝福语赠言给老师简短
18 新娘上头祝福语大全简短