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