Bits. Write a program Bits.java that takes an integer command-line argument N an
ID: 3809743 • Letter: B
Question
Bits. Write a program Bits.java that takes an integer command-line argument N and uses a while loop to compute the number of times you need to divide N by 2 until it is strictly less than 1. Print out an error message if N is negative.
Remark: This computes the number of bits in the binary representation of N, which also equals 1 + floor(log2 N) when N is positive. This quantity arises in information theory and the analysis of algorithms.
% java Bits 0 % java Bits 8 0 4 % java Bits 1 % java Bits 16 1 5 % java Bits 2 % java Bits 1000 2 10 % java Bits 4 % java Bits -23 3 Illegal input
Explanation / Answer
Bits.java
public class Bits {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int count = 0;
if(n < 0){
System.out.println("Illegal Input");
}
else{
while( n > 0){
count++;
n = n/2;
}
System.out.println("Number of times we need to divide: "+count );
}
}
}
Output:
java Bits 16
4
java Bits 1000
10
java Bits -23
Illegal Input
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.