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);

更新于: 2020年6月27日

301 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.