Q:

Java program to round off an integer number to the next lower multiple of 2

belongs to collection: Java Basic Programs

0

Java program to round off an integer number to the next lower multiple of 2

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to round off an integer number to the next lower multiple of 2 is given below. The given program is compiled and executed successfully.

// Java program to round off an integer number to 
// the next lower multiple of 2

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int tmp = 1;
    int num = 0;
    int i = 0;

    System.out.printf("Enter Number: ");
    num = SC.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.printf("Result is: %d\n", num);
  }
}

Output:

Enter Number: 35
Result is: 32

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to count the number of leading zeros ... >>
<< Java program to find the highest bit set for a giv...