Write Java program to Round off an integer number to the next lower multiple of 2
This program takes an integer input from the user and rounds it off to the nearest power of 2. The logic used in this program is as follows:
- First, the program checks if the input integer is positive or negative.
- If the integer is positive, the program checks for the nearest power of 2 by left shifting 1 until it becomes greater than the input integer divided by 2. The left-shift operator (<<) shifts the bits of a number to the left by a specified number of positions. For example, if we have the number 2 (0010 in binary), then 2 << 1 would result in 4 (0100 in binary), and 2 << 2 would result in 8 (1000 in binary).
- If the integer is negative, the program first converts it to its two's complement representation by taking the bitwise complement and adding 1. Then, it finds the nearest power of 2 in the same way as for a positive integer. Finally, it converts the result back to the original negative integer by first taking the bitwise complement and adding 1 again.
Source Code
import java.util.Scanner;
public class RoundOff_Integer
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tmp = 1;
int num = 0;
int i = 0;
System.out.printf("Enter the Number : ");
num = input.nextInt();
if (num > 0)
{
for (; tmp <= num >> 1;)
{
tmp = tmp << 1;
}
num = tmp;
}
else
{
num = ~num;
num = num + 1;
for (; tmp <= num >> 1;)
{
tmp = tmp << 1;
}
tmp = tmp << 1;
tmp = ~tmp;
tmp = tmp + 1;
num = tmp;
}
System.out.println("Result is : "+ num);
}
}
Output
Enter the Number : 20
Result is : 16