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);
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP