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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
5 带马的祝福语简短
10 女孩自己生日祝福语简短
11 回家祝福语简短老师发言
12 女儿成年祝福语简短霸气
13 中秋送礼的祝福语简短
14 感谢朋友的祝福语简短
15 简短浪漫的生日祝福语
16 三八祝福语简短文案
17 佛学生日简短祝福语
18 晚安好梦祝福语简短