计数二进制数中连续1的数量
Count number of consecutive 1 in a binary number
我被要求将自然数转换为二进制表示,并计算二进制表示中连续的'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 )
相关文章:
- visual在c++中将十进制数转换为二进制数
- 二进制数之和(使用C样式字符串)
- 以 10 c++ 为基数显示 1024 位二进制数
- 二进制数和位标志'x'
- C++ 二进制数到整数值的数组
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- dev如何在C++中比较二进制数
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 向后打印二进制数
- 使用位黑客反转二进制数
- 添加两个二进制数(整数数组)
- 从 0 到 n 的二进制数,具有相同数量的字符/
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 所有测试用例都将小数点转换为二进制数
- 尝试将二进制数组转换为十六进制C++然后打印结果
- 如何缩放二进制数组以保留值
- 计数二进制数中连续1的数量
- 使用堆栈将十进制数转换为二进制数
- C++ 添加二进制数 - 分段错误
- 获取下一个非连续的二进制数