C# 程序用于查找给定整数二进制表示形式中连续 1 的最长长度
为了获取连续的 1,使用按位左移运算符。下面是我们的十进制数。
i = (i & (i << 1));
循环上述代码,直到 I 的值为 0,并使用变量获取长度;这里的计数。
while (i != 0) {
i = (i & (i << 1));
count++;
}这里,我们采取的示例是 150。
150 的二进制为 10010110。因此,我们有两个连续的 1。
示例
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP