Java: Returns the largest integer but not larger than the base-2 logarithm of a specified integer
Largest Integer Base-2 Logarithm
Write a Java program that returns the largest integer but not larger than the base-2 logarithm of a given integer.
Original Number: 2350
Result: 11
Sample Solution:
Java Code:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Initializing an integer variable 'n' with the value 2350
int n = 2350;
// Displaying the original number
System.out.printf("Original Number: %d\n", n);
// Initializing a variable to count the number of right shifts
int shift_right_count = 0;
// Performing right shift operations until 'n' becomes zero
do {
n >>= 1; // Right shifting 'n' by 1 bit
shift_right_count++; // Incrementing the shift count
} while (n != 0); // Loop continues until 'n' becomes zero
shift_right_count--; // Decrementing the shift count by 1 to correct the count
// Displaying the final result (shift count)
System.out.printf("Result: %s\r\n", shift_right_count);
}
}
Sample Output: Original Number: 2350 Result: 11
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to find the smallest integer not less than the base-2 logarithm of a given number.
- Write a Java program to compute the floor of the base-2 logarithm using a recursive approach.
- Write a Java program to calculate the floor of the logarithm of a number for an arbitrary base without built-in functions.
- Write a Java program to compute the floor of the base-2 logarithm without using any math library methods.
Go to:
PREV : Transpose 2D Array.
NEXT : GCD Using Euclid's Algorithm.
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.