Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ตรวจสอบ 1 ติดกัน K ตัวในเลขฐานสอง

ตรวจสอบว่ามีบิต 1 ติดกัน K ตัวในการแทนค่าบाइनนารีหรือไม่

ใช้ bool array แทนบิต (true=1, false=0)

อัลกอริทึม

int count = 0, maxCount = 0;
foreach (bool bit in bits) {
    if (bit) {
        count++;
        maxCount = Math.Max(maxCount, count);
    } else {
        count = 0; // รีเซ็ตเมื่อเจอ 0
    }
}
// maxCount = จำนวน 1 ติดกันสูงสุด

ตัวอย่างโค้ดเต็ม

using System;
class MyApplication {
    static int CountConsecutiveOnes(bool[] bits) {
        int count = 0, maxCount = 0;
        for (int i = 0; i < bits.Length; i++) {
            if (!bits[i]) count = 0;
            else {
                count++;
                maxCount = Math.Max(maxCount, count);
            }
        }
        return maxCount;
    }
    public static void Main() {
        bool[] bits = {false, true, false, false, false, true, true, true};
        Console.Write("Consecutive 1's = " + CountConsecutiveOnes(bits));
    }
}

ผลลัพธ์

Consecutive 1's = 3

การประยุกต์: สำหรับ integer จริง ให้แปลงเป็น binary string ก่อน หรือใช้ bitwise operations