要获取连续的1,请使用按位左移运算符。这是我们的十进制数字。
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;
}
//驱动程式码
public static void Main() {
//二进制或150是10010110-
Console.WriteLine(findConsecutive(150));
}
}输出结果
2