ในการดึงค่า 1 ติดต่อกัน ให้ใช้ Bitwise Left Shift Operator นี่คือเลขทศนิยมของเรา
i = (i & (i << 1));
วนซ้ำด้านบนจนค่าของ I เป็น 0 และดึงความยาวโดยใช้ตัวแปร นับที่นี่
while (i != 0) {
i = (i & (i << 1));
count++;
} ตัวอย่างที่เรานำมาคือ 150
เลขฐานสองของ 150 คือ 10010110 ดังนั้นเราจึงมีเลขฐานสองสองตัวติดต่อกัน
ตัวอย่าง
using System;
class Demo {
private static int findConsecutive(int i) {
int count = 0;
while (i != 0) {
i = (i & (i < 1));
count++;
}
return count;
}
// Driver code
public static void Main() {
// Binary or 150 is 10010110
Console.WriteLine(findConsecutive(150));
}
} ผลลัพธ์
2