简体   繁体   English

计算二进制数中连续1的数目

[英]Count number of consecutive 1 in a binary number

I am asked to convert a natural number to binary representation and count the number of consecutive '1' in the binary representation. 我被要求将自然数转换为二进制表示形式,并计算二进制表示形式中连续的“ 1”的数量。 For example :- input number is '5' , then its output should be '1'. 例如:-输入数字为'5',则其输出应为'1'。 I don't know where is the problem but its failing in these two cases '524283' and '524275'. 我不知道问题出在哪里,但在这两个案例“ 524283”和“ 524275”中都失败了。 This is my code in c++ :- 这是我在C ++中的代码:-

 int main(){
int n,repeat=0,count=0,max=0;
cin >> n;
std::stack<int> binNum;
while(n>0)
    {
    binNum.push(n%2);
    n=n/2;
}
while(!binNum.empty())
    {
    if( !binNum.empty() && binNum.top()==1 )
        {
        count++;
        if(repeat>=count)
            {
            max=repeat;
        }
        else
            {
            max=count;
        }
        repeat=count;
        binNum.pop();
        if(!binNum.empty() && binNum.top()==0)
            {
            count=0;
            binNum.pop();
        }
    }
    else
        {
        binNum.pop();
    }
}
cout<<max;
return 0;

} }

Change 更改

if(binNum.top()==1 && !binNum.empty())

to

if(!binNum.empty() && binNum.top()==1 )

If the stack is empty, you don't want to get the top first and then check whether it is empty. 如果堆栈为空,则您不想先获取顶部,然后再检查其是否为空。

Similarly, change 同样,改变

    if(binNum.top()==0 && !binNum.empty())

to

    if(binNum.empty() && binNum.top()==0 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM