请需要伪代码帮助
给定一个二进制数,计算最大块。 例如: 二进制表示 = 11111 最大块长度 = 5
二进制表示 = 10111011 最大块长度 = 3
max block 表示连续 1 或 0 的数量。所以 00010000 的最大块数为 4
以上是我的教授给出的仅有的 2 个例子。 "计算二进制的最大块长度 这就是他所说的。我假设这也包括 0。我真的不知道该怎么做。
这就是我想到的:
让 B = 收到的二进制数。 将B放入A[]中,每个数字代表一个元素。 假设 A[0] = 1 对于 A.length - 1 只要不为零就计数 1 秒 max = 1 秒的总数。 只要没有碰到 1 就计数 0 如有必要,更新最大值 重复。
Given a binary number calculate the maximum block.
For ex:
Binary representation = 11111
Maximum block length = 5
Binary representation = 10111011
Maximum block length = 3
max block means the number of consecutive 1's or 0's. So 00010000 would have a max block of 4
Above are the only 2 examples my professor gave.
"Compute the maximum block length of the binary
representation." This is what he said. I'm assuming this includes 0s as well. I really don't know how to go about it.
This is what I have come up with:
Let B = the binary number received.
put B into A[], each digit representing an element.
assume A[0] = 1
for A.length - 1
count 1s as long as not hit zero
max = total count of 1s.
count 0s as long as not hit 1
update max if necessary
repeat.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
遍历序列,跟踪:
最后一个数字是什么
当前块的长度(如果最后一个数字!=当前数字,则重置)
>
到目前为止最长块的长度(直到并包括当前块)
你必须处理的边缘情况with 是第一个元素,它没有前导元素,因此您必须在进入循环之前将第一个“最后一个数字”设置为该元素,循环应该只从第二个元素迭代到末尾。
Go through the sequence, keeping track of:
What the last number was
The length of the current block (which gets reset if last number != current number)
The length of the longest block so far (up to and including the current block)
Edge case you'll have to deal with is the first element, which has no predecessor, so you'll have to set the first 'last number' to that before you hit the loop, which should only iterate through from the second to the end.
在 CI 中会这样做
In C I would do it like this
所以我想通了。这是完整的代码。它获取用户输入,将十进制数转换为二进制数,计算 1 的最大块数并计算 1 的总数。还有一个小错误,如果输入 0,则应该接受输入,并且程序应该正常工作,但事实并非如此。
So I figured it out. Here's the complete code. This gets the user input, converts the decimal number to binary, counts the maximum block of 1's and counts total 1's. There is still small bug, input should be accepted if 0 is entered and the program should work properly, but it does not.