

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Count set bits in an integer
To count set bits in an integer, the Java code is as follows −
Example
import java.io.*; public class Demo{ static int set_bits_count(int num){ int count = 0; while (num > 0){ num &= (num - 1); count++; } return count; } public static void main(String args[]){ int num =11; System.out.println("The number of set bits in 11 is "); System.out.println(set_bits_count(num)); } }
Output
The number of set bits in 11 is 3
The above is an implementation of the Brian Kernighan algorithm. A class named Demo contains a static function named ‘set_bits_count’. This function checks if the number is 0, and if not, assigns a variable named ‘count’ to 0. It performs the ‘and’ operation on the number and the number decremented by 1.
Next, the ‘count’ value is decremented after this operation. In the end, the count value is returned. In the main function, the value whose set bits need to be found is defined. The function is called by passing the number as a parameter. Relevant messages are displayed on the console.
- Related Questions & Answers
- Python Program to Count set bits in an integer
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- C/C++ Program to the Count set bits in an integer?
- Count set bits in an integer in C++
- Java Program to Count Number of Digits in an Integer
- C# program to count total set bits in a number
- Sort an array according to count of set bits in C++
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- Java program to count total bits in a number
- Java program to reverse bits of a positive integer number
- Python Count set bits in a range?
- Java Program to Print an Integer
- Program to convert set of Integer to Array of Integer in Java
Advertisements