Program Discussion :: Bitwise Operator
12 / 15
Write an efficient program to count the number of bits set in an integer number
Answer:
#include
using namespace std;
// count the no. of set bits in a positive integer
int countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
//main
int main() {
unsigned int num = 6;
unsigned int no_set_bits = countSetBits(num);
cout
Asked In ::
Language:
Jyoti Choudhary
13 May, 2017 8:46 PM
import java.util.*;
class CountSetBits
{
public static void main(String args[])
{
int n, count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number ");
n = in.nextLine();
while(n)
{
if(n&1)
count++;
n>>=1;
}
System.out.println("number of bits set is"+count "in %d" +n );
}
}
Language:
Varun
1 Jul, 2017 11:07 PM
<!DOCTYPE html>
<html>
<body>
<?php
function Bit_in_integer() {
$no = 60; /* input no who Binary equivalent and no of its to be calculate */
echo "Integer no whose bits to be calculate : " . $no."<br/>";
$binary_no= decbin ($no); /* function to convert given no into binary */
echo "Binary equivalent of given integer no is : " . $binary_no . "<br/>";
$count =0;
while ($binary_no )
{
if (($binary_no & 1) == 1)
{
$count++;
}
$binary_no = $binary_no >> 1;
}
echo $count ;
}
Bit_in_integer() ; /* function calling */
?>
</body>
</html>
Language:
Rahul
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include <string.h>
int countSetBits(unsigned int n)
{
unsigned int c; /* the total bits set in n */
for (c = 0; n; n >>= 1)
{
c += n & 1;
}
return c;
}
int main(void)
{
unsigned int n;
printf("Enter a positive integer: ");
scanf("%u", &n);
printf("%d\n", countSetBits(n));
}
Language:
Neha
7 Jul, 2017 9:30 AM
#include<iostream>
using namespace std;
// count the no. of set bits in a positive integer
int countSetBits(unsigned int num) {
unsigned int count = 0;
while (num) {
// bitwise AND operation to check if the
// leftmost bit is set or not
// if set, increment the count
count += num & 1;
// left shift the nm by one position
num >>= 1;
}
return count;
}
//main
int main() {
unsigned int num = 6;
unsigned int no_set_bits = countSetBits(num);
cout<<"\nNo. of set bits :: "<<no_set_bits;
cout<<endl;
return 0;
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.io.*;
public class CountNumberOfBits
{
static int CountNumberOfBits(int num)
{
int count = 0;
while (num > 0)
{
count += num & 1;
num >>= 1;
}
return count;
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int num=Integer.parseInt(br.readLine());
System.out.println(CountNumberOfBits(num));
}
}