计数二进制数中连续1的数量

Count number of consecutive 1 in a binary number

本文关键字:二进制数 连续      更新时间:2023-10-16

我被要求将自然数转换为二进制表示,并计算二进制表示中连续的'1'数量。例如: - 输入号为" 5",然后其输出应为" 1"。我不知道问题在哪里,但是在这两种情况下," 524283"answers" 524275"失败了。这是我在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;

}

更改

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

to

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

如果堆栈为空,则不想先获得顶部,然后检查它是否为空。

同样,更改

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

to

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