Java程序以给定整数的二进制表示形式找到最长连续1的长度
给定整数的二进制表示形式中,最长连续1的长度涉及一起出现的最长1序列的长度。一个例子如下:
Number = 13 Binary representation = 1101
二进制表示形式中最长的连续1的长度为13=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变量中。最后,显示计数值。证明这一点的代码片段如下所示-
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);热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短