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