
要检查二进制数中是否有连续的 1,需要检查 0 和 1。
首先,为 0 和 1 设置一个 bool 数组即假与真 –
bool []myArr = {false, true, false, false, false, true, true, true};
对于 0,将计数设置为 0 –
if (myArr[i] == false) count = 0;
对于 1,增加计数并设置结果。 Max() 方法返回两个数字中较大的一个 –
count++;res = Math.Max(res, count);
示例
以下是检查二进制数中是否有 K 个连续 1 的示例 –
现场演示
using System;class MyApplication { static int count(bool []myArr, int num) { int myCount = 0, res = 0; for (int i = 0; i < num; i++) { if (myArr[i] == false) myCount = 0; else { myCount++; res = Math.Max(res, myCount); } } return res; } public static void Main() { bool []myArr = {false, true, false, false, false, true, true, true}; int num = myArr.Length; Console.Write("Consecutive 1's = "+count(myArr, num)); }}
输出
Consecutive 1's = 3
以上就是C#程序检查二进制数中是否有K个连续的1的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1435395.html
微信扫一扫
支付宝扫一扫