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.