Kiểm tra xem trong biểu diễn nhị phân của một số (hoặc mảng bool) có tồn tại K bit 1 liên tiếp hay không. Dùng biến đếm tăng khi gặp 1, reset về 0 khi gặp 0.
Mã nguồn (dùng mảng bool)
using System;
class MyApplication {
// Trả về độ dài dãy 1 liên tiếp dài nhất
static int MaxConsecutiveOnes(bool[] bits) {
int current = 0, max = 0;
foreach (bool bit in bits) {
if (bit) {
current++;
if (current > max) max = current;
} else {
current = 0;
}
}
return max;
}
public static void Main() {
// false=0, true=1
bool[] myArr = { false, true, false, false, false, true, true, true };
int maxOnes = MaxConsecutiveOnes(myArr);
Console.WriteLine("Dãy 1 liên tiếp dài nhất: " + maxOnes);
}
}
Kết quả
Dãy 1 liên tiếp dài nhất: 3
Mảng: 0, 1, 0, 0, 0, 1, 1, 1 → dãy 1 dài nhất là 3 (3 bit 1 cuối)
Áp dụng cho số nguyên (int/long)
static int MaxConsecutiveOnesInt(int n) {
int current = 0, max = 0;
while (n != 0) {
if ((n & 1) == 1) {
current++;
if (current > max) max = current;
} else {
current = 0;
}
n >>= 1; // Dịch phải kiểm tra bit tiếp theo
}
return max;
}
// Test
Console.WriteLine(MaxConsecutiveOnesInt(0b1101110)); // 3 (111 ở giữa)
Console.WriteLine(MaxConsecutiveOnesInt(0b1111)); // 4
Kiểm tra có ít nhất K bit 1 liên tiếp
static bool HasKConsecutiveOnes(int n, int k) {
int current = 0;
while (n != 0) {
if ((n & 1) == 1) {
current++;
if (current >= k) return true;
} else {
current = 0;
}
n >>= 1;
}
return false;
}
Lưu ý
- Code gốc dùng mảng
bool[]— phù hợp khi đã có mảng bit. Với số nguyên, dùng bitwise& 1+>>= 1hiệu quả hơn. - Dịch phải
>>trên signed int là arithmetic shift — với số âm sẽ lặp vô hạn do bit dấu = 1. Nên dùnguinthoặcn &= n - 1trick. Math.Max(res, count)trong code gốc thay bằngif (current > max) max = currentnhanh hơn (tránh gọi hàm).