简体   繁体   中英

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. For example :- input number is '5' , then its output should be '1'. I don't know where is the problem but its failing in these two cases '524283' and '524275'. This is my code in 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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