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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短