A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Java program to find the number of bits required to represent a number
Q:

Java program to find the number of bits required to represent a number

0

Java program to find the number of bits required to represent a number

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 find the number of bits required to represent a number is given below. The given program is compiled and executed successfully.

// Java program to find the number of bits 
// required to represent a number

import java.util.Scanner;

public class Main {
  static int countBit(int n) {
    int count = 0, i;

    if (n == 0)
      return 0;

    for (i = 0; i < 32; i++) {
      if (((1 << i) & n) != 0)
        count = i;
    }
    return ++count;
  }

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

    int num = 0;

    System.out.printf("Enter an integer number: ");
    num = SC.nextInt();

    System.out.printf("Total number of bits required: %d\n", countBit(num));
  }
}

Output:

Enter an integer number: 255
Total number of bits required: 8

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contain two static methods countBit() and main().

The countBit() method is used to find the total number of bits required to represent the specified number and return the result to the calling function.

 

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now