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);热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短