【问题标题】:Count number of consecutive 1 in a binary number计算二进制数中连续 1 的个数
【发布时间】:2017-03-10 06:12:13
【问题描述】:

我被要求将自然数转换为二进制表示并计算二进制表示中连续“1”的数量。例如:- 输入数字是 '5' ,那么它的输出应该是 '1'。我不知道问题出在哪里,但在“524283”和“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;

}

【问题讨论】:

标签: c++ stl stack


【解决方案1】:

改变

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

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

如果栈是空的,不要先取到栈顶再检查是否为空。

同样,改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2015-05-01
    • 2019-04-23
    • 2015-07-09
    相关资源
    最近更新 更多