输入一个10进制数字,请计算该数字对应二进制中0的个数,注意左数第一个1之前的所有0都不需要计算。不需要考虑负数的情况。
输入:要计算的十进制非负数
输出:
二进制中第一个1之后0 的个数
思路:一个整形32位最多移动32次,先找出最左边一个1的位置,判断条件 a=1<<i;if((num&a)==a) 然后设立标志位开始计数0的个数
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<set>
using namespace std;
//思路一个整形32位最多移动32次,先找出最左边一个1的位置,判断条件 a=1<<i;if((num&a)==a) 然后设立标志位开始计数0的个数
int numberOfBitZero(unsigned num)
{
unsigned int a=1;
bool flag=false;
int count=0;
char buffer1[100];
for(int i=31;i>=0;i--)
{
a=1<<i;
if(num&a)//此次的条件尤其注意,可以写成if((num&a)==a)
{
flag=true;
}
if(flag==true)
{
if((num&a)==0)
{
count++;
}
}
}
return count;
}
int main()
{
unsigned int a;
cin>>a;
cout<<numberOfBitZero(a)<<endl;
return 0;
}