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 婆婆高寿祝福语大全简短