Java程序查找给定整数二进制表示中连续最长1的长度
给定整数的二进制表示中连续最长1的长度涉及到一起出现的1的最长序列的长度。如下所示示例:
Number = 13 Binary representation = 1101
13的二进制表示中连续最长1的长度 = 2
演示此功能的程序如下所示:
示例
public class Example {
public static void main(String strings[]) {
int num = 55;
int n = num;
int count = 0;
while (num!=0) {
num = (num & (num << 1));
count++;
}
System.out.println("The length of the longest consecutive 1's in binary representation of " + n + " is: " + count);
}
}输出
The length of the longest consecutive 1's in binary representation of 55 is: 3
现在让我们了解上述程序。
定义数字的值。然后,使用while循环查找数字二进制表示中连续最长1的长度,并将结果存储在count变量中。最后,显示count的值。演示此功能的代码片段如下所示:
int num = 55;
int n = num;
int count = 0;
while (num!=0) {
num = (num & (num << 1));
count++;
}
System.out.println("The length of the longest consecutive 1's in binary representation of " + n + " is: " + count);
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP