Java 程式來計算一個數字中的總位數


一個數字中的總位數可以透過使用它的二進位制表示來計算。以下是一個示例:

Number = 9
Binary representation = 1001
Total bits = 4

展示該功能的程式如下。

示例

即時演示

public class Example {
   public static void main(String[] arg) {
      int num = 10;
      int n = num;
      int count = 0;
      while (num != 0) {
         count++;
         num >>= 1;
      } 
      System.out.print("The total bits in " + n + " are " + count);
   }
}

輸出

The total bits in 10 are 4

接下來,讓我們理解這個程式。

首先,定義數字。然後,該數字中的總位數儲存在 count 中。這是透過在 while 迴圈中使用右移運算子來完成的。最後,顯示總位數。展示該功能的程式碼片段如下:

int num = 10;
int n = num;
int count = 0;
while (num != 0) {
   count++;
   num >>= 1;
}
System.out.print("The total bits in " + n + " are " + count);

更新日期:2019-07-30

702 次瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始
廣告