要检查二进制数中是否有连续的 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的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号