编写一个高效的程序,以整数的二进制表示形式计算1的数量。
例子 :
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 13 is 1101 and has 3 set bits
1.简单方法遍历整数中的所有位,检查是否设置了位,然后再递增设置的位计数。参见下面的程序。
C++
// C++ program to Count set
// bits in an integer
#include
using namespace std;
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
cout << countSetBits(i);
return 0;
}
// This code is contributed
// by Akanksha Rai
C
// C program to Count set
// bits in an integer
#include
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
return 0;
}
Java
// Java program to Count set
// bits in an integer
import java.io.*;
class countSetBits {
/* Function to get no of set
bits in binary representation
of positive integer n */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}
// This code is contributed by Anshika Goyal.
Python3
# Python3 program to Count set
# bits in an integer
# Function to get no of set bits in binary
# representation of positive integer n */
def countSetBits(n):
count = 0
while (n):
count += n & 1
n >>= 1
return count
# Program to test function countSetBits */
i = 9
print(countSetBits(i))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to Count set
// bits in an integer
using System;
class GFG {
// Function to get no of set
// bits in binary representation
// of positive integer n
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
// Driver Code
public static void Main()
{
int i = 9;
Console.Write(countSetBits(i));
}
}
// This code is contributed by Sam007
PHP
>= 1;
}
return $count;
}
// Driver Code
$i = 9;
echo countSetBits($i);
// This code is contributed by ajit
?>
Javascript
C++
// cpp implementation of recursive
// approach to find the number
// of set bits in binary representation
// of positive integer n
#include
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// driver code
int main()
{
// get value from user
int n = 9;
// function calling
cout << countSetBits(n);
return 0;
}
// This code is contributed by Raj.
Java
// Java implementation of recursive
// approach to find the number
// of set bits in binary representation
// of positive integer n
import java.io.*;
class GFG {
// recursive function to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// Driver code
public static void main(String[] args)
{
// get value from user
int n = 9;
// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributes by sunnysingh
Python3
# Python3 implementation of recursive
# approach to find the number of set
# bits in binary representation of
# positive integer n
def countSetBits( n):
# base case
if (n == 0):
return 0
else:
# if last bit set add 1 else
# add 0
return (n & 1) + countSetBits(n >> 1)
# Get value from user
n = 9
# Function calling
print( countSetBits(n))
# This code is contributed by sunnysingh
C#
// C# implementation of recursive
// approach to find the number of
// set bits in binary representation
// of positive integer n
using System;
class GFG {
// recursive function
// to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set
// add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// Driver code
static public void Main()
{
// get value
// from user
int n = 9;
// function calling
Console.WriteLine(countSetBits(n));
}
}
// This code is contributed by aj_36
PHP
> 1);
}
// Driver code
// get value from user
$n = 9;
// function calling
echo countSetBits($n);
// This code is contributed by m_kit.
?>
Javascript
C++
// C++ program to Count set
// bits in an integer
#include
using namespace std;
class gfg {
/* Function to get no of set bits in binary
representation of passed binary no. */
public:
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};
/* Program to test function countSetBits */
int main()
{
gfg g;
int i = 9;
cout << g.countSetBits(i);
return 0;
}
C
// C program to Count set
// bits in an integer
#include
/* Function to get no of set bits in binary
representation of passed binary no. */
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
getchar();
return 0;
}
Java
// Java program to Count set
// bits in an integer
import java.io.*;
class countSetBits {
/* Function to get no of set
bits in binary representation
of passed binary no. */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}
// This code is contributed by Anshika Goyal.
Python3
# Function to get no of set bits in binary
# representation of passed binary no. */
def countSetBits(n):
count = 0
while (n):
n &= (n-1)
count+= 1
return count
# Program to test function countSetBits
i = 9
print(countSetBits(i))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to Count set
// bits in an integer
using System;
class GFG {
/* Function to get no of set
bits in binary representation
of passed binary no. */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// Driver Code
static public void Main()
{
int i = 9;
Console.WriteLine(countSetBits(i));
}
}
// This code is contributed by ajit
PHP
Javascript
C++
// CPP implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan’s Algorithm
#include
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// driver code
int main()
{
// get value from user
int n = 9;
// function calling
cout << countSetBits(n);
return 0;
}
// This code is contributed by Raj.
Java
// Java implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
import java.io.*;
class GFG {
// recursive function to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// Driver function
public static void main(String[] args)
{
// get value from user
int n = 9;
// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributed by sunnysingh
Python3
# Python3 implementation for
# recursive approach to find
# the number of set bits using
# Brian Kernighan’s Algorithm
# recursive function to count
# set bits
def countSetBits(n):
# base case
if (n == 0):
return 0
else:
return 1 + countSetBits(n & (n - 1))
# Get value from user
n = 9
# function calling
print(countSetBits(n))
# This code is contributed by sunnysingh
C#
// C# implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
using System;
class GFG {
// recursive function
// to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// Driver Code
static public void Main()
{
// get value from user
int n = 9;
// function calling
Console.WriteLine(countSetBits(n));
}
}
// This code is contributed by aj_36
PHP
Javascript
C++
// C++ implementation of the approach
#include
using namespace std;
int BitsSetTable256[256];
// Function to initialise the lookup table
void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) +
BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff] +
BitsSetTable256[(n >> 8) & 0xff] +
BitsSetTable256[(n >> 16) & 0xff] +
BitsSetTable256[n >> 24]);
}
// Driver code
int main()
{
// Initialise the lookup table
initialize();
int n = 9;
cout << countSetBits(n);
}
// This code is contributed by Sanjit_Kumar
Java
// Java implementation of the approach
class GFG {
// Lookup table
static int[] BitsSetTable256 = new int[256];
// Function to initialise the lookup table
public static void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++) {
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}
// Driver code
public static void main(String[] args)
{
// Initialise the lookup table
initialize();
int n = 9;
System.out.print(countSetBits(n));
}
}
Python
# Python implementation of the approach
BitsSetTable256 = [0] * 256
# Function to initialise the lookup table
def initialize():
# To initially generate the
# table algorithmically
BitsSetTable256[0] = 0
for i in range(256):
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2]
# Function to return the count
# of set bits in n
def countSetBits(n):
return (BitsSetTable256[n & 0xff] +
BitsSetTable256[(n >> 8) & 0xff] +
BitsSetTable256[(n >> 16) & 0xff] +
BitsSetTable256[n >> 24])
# Driver code
# Initialise the lookup table
initialize()
n = 9
print(countSetBits(n))
# This code is contributed by SHUBHAMSINGH10
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Lookup table
static int[] BitsSetTable256 = new int[256];
// Function to initialise the lookup table
public static void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}
// Driver code
public static void Main(String[] args)
{
// Initialise the lookup table
initialize();
int n = 9;
Console.Write(countSetBits(n));
}
}
// This code is contributed by 29AjayKumar
Javascript
C++
// C++ program to demonstrate __builtin_popcount()
#include
using namespace std;
int main()
{
cout << __builtin_popcount(4) << endl;
cout << __builtin_popcount(15);
return 0;
}
Java
// java program to demonstrate
// __builtin_popcount()
import java.io.*;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println(Integer.bitCount(4));
System.out.println(Integer.bitCount(15));
}
}
// This code is contributed by Raj
Python3
# Python3 program to demonstrate __builtin_popcount()
print(bin(4).count('1'));
print(bin(15).count('1'));
# This code is Contributed by mits
C#
// C# program to demonstrate
// __builtin_popcount()
using System;
using System.Linq;
class GFG {
// Driver code
public static void Main()
{
Console.WriteLine(Convert.ToString(4, 2).Count(c = > c == '1'));
Console.WriteLine(Convert.ToString(15, 2).Count(c = > c == '1'));
}
}
// This code is contributed by mits
PHP
C++
// C++ program to count set bits by pre-storing
// count set bits in nibbles.
#include
using namespace std;
int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
unsigned int countSetBitsRec(unsigned int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
int main()
{
int num = 31;
cout << countSetBitsRec(num);
return 0;
}
// This code is contributed by rathbhupendra
C
// C program to count set bits by pre-storing
// count set bits in nibbles.
#include
int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
unsigned int countSetBitsRec(unsigned int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
int main()
{
int num = 31;
printf("%d\n", countSetBitsRec(num));
}
Java
// Java program to count set bits by pre-storing
// count set bits in nibbles.
class GFG {
static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2,
3, 1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
static int countSetBitsRec(int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
public static void main(String[] args)
{
int num = 31;
System.out.println(countSetBitsRec(num));
}
}
// this code is contributed by mits
Python3
# Python3 program to count set bits by pre-storing
# count set bits in nibbles.
num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
# Recursively get nibble of a given number
# and map them in the array
def countSetBitsRec(num):
nibble = 0;
if(0 == num):
return num_to_bits[0];
# Find last nibble
nibble = num & 0xf;
# Use pre-stored values to find count
# in last nibble plus recursively add
# remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
# Driver code
num = 31;
print(countSetBitsRec(num));
# this code is contributed by mits
C#
// C# program to count set bits by pre-storing
// count set bits in nibbles.
class GFG {
static int[] num_to_bits = new int[16] { 0, 1, 1, 2, 1, 2, 2,
3, 1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
static int countSetBitsRec(int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
static void Main()
{
int num = 31;
System.Console.WriteLine(countSetBitsRec(num));
}
}
// this code is contributed by mits
PHP
> 4);
}
// Driver code
$num = 31;
echo (countSetBitsRec($num));
// This code is contributed by mits
?>
C
#include
// Check each bit in a number is set or not
// and return the total count of the set bits.
int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < sizeof(int) * 8; i++) {
if (N & (1 << i))
count++;
}
return count;
}
// Driver Code
int main()
{
int N = 15;
printf("%d", countSetBits(N));
return 0;
}
C++
#include
using namespace std;
// Check each bit in a number is set or not
// and return the total count of the set bits.
int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < sizeof(int) * 8; i++) {
if (N & (1 << i))
count++;
}
return count;
}
int main()
{
int N = 15;
cout << countSetBits(N) << endl;
return 0;
}
Java
public class GFG
{
// Check each bit in a number is set or not
// and return the total count of the set bits.
static int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < 4 * 8; i++)
{
if ((N & (1 << i)) != 0)
count++;
}
return count;
}
// Driver code
public static void main(String[] args)
{
int N = 15;
System.out.println(countSetBits(N));
}
}
// This code is contributed by divyeshrabadiya07.
Python3
# Check each bit in a number is set or not
# and return the total count of the set bits
def countSetBits(N):
count = 0
# (1 << i) = pow(2, i)
for i in range(4*8):
if(N & (1 << i)):
count += 1
return count
# Driver code
N = 15
print(countSetBits(N))
# This code is contributed by avanitrachhadiya2155
C#
using System;
class GFG
{
// Check each bit in a number is set or not
// and return the total count of the set bits.
static int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < 4 * 8; i++)
{
if ((N & (1 << i)) != 0)
count++;
}
return count;
}
// Driver code
static void Main()
{
int N = 15;
Console.WriteLine(countSetBits(N));
}
}
// This code is contributed by divyesh072019.
Javascript
输出 :
2
时间复杂度: (-)(logn)(logn的Theta)
递归方法:
C++
// cpp implementation of recursive
// approach to find the number
// of set bits in binary representation
// of positive integer n
#include
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// driver code
int main()
{
// get value from user
int n = 9;
// function calling
cout << countSetBits(n);
return 0;
}
// This code is contributed by Raj.
Java
// Java implementation of recursive
// approach to find the number
// of set bits in binary representation
// of positive integer n
import java.io.*;
class GFG {
// recursive function to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// Driver code
public static void main(String[] args)
{
// get value from user
int n = 9;
// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributes by sunnysingh
Python3
# Python3 implementation of recursive
# approach to find the number of set
# bits in binary representation of
# positive integer n
def countSetBits( n):
# base case
if (n == 0):
return 0
else:
# if last bit set add 1 else
# add 0
return (n & 1) + countSetBits(n >> 1)
# Get value from user
n = 9
# Function calling
print( countSetBits(n))
# This code is contributed by sunnysingh
C#
// C# implementation of recursive
// approach to find the number of
// set bits in binary representation
// of positive integer n
using System;
class GFG {
// recursive function
// to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set
// add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// Driver code
static public void Main()
{
// get value
// from user
int n = 9;
// function calling
Console.WriteLine(countSetBits(n));
}
}
// This code is contributed by aj_36
的PHP
> 1);
}
// Driver code
// get value from user
$n = 9;
// function calling
echo countSetBits($n);
// This code is contributed by m_kit.
?>
Java脚本
输出 :
2
2. Brian Kernighan的算法:
从十进制数中减去1将翻转最右边的设置位(即1)之后的所有位,包括最右边的设置位。
例如 :
10的二进位是00001010
二进制9是00001001
8的二进位是00001000
二进制中的7是00000111
因此,如果我们将数字减1并对其本身按位与(n&(n-1)),则会取消设置最右边的位。如果我们在循环中执行n&(n-1)并计算循环执行的次数,我们将获得设置的位数。
该解决方案的优点在于,它循环的次数等于给定整数中的设置位数。
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count
Brian Kernighan算法的实现:
C++
// C++ program to Count set
// bits in an integer
#include
using namespace std;
class gfg {
/* Function to get no of set bits in binary
representation of passed binary no. */
public:
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};
/* Program to test function countSetBits */
int main()
{
gfg g;
int i = 9;
cout << g.countSetBits(i);
return 0;
}
C
// C program to Count set
// bits in an integer
#include
/* Function to get no of set bits in binary
representation of passed binary no. */
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
getchar();
return 0;
}
Java
// Java program to Count set
// bits in an integer
import java.io.*;
class countSetBits {
/* Function to get no of set
bits in binary representation
of passed binary no. */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}
// This code is contributed by Anshika Goyal.
Python3
# Function to get no of set bits in binary
# representation of passed binary no. */
def countSetBits(n):
count = 0
while (n):
n &= (n-1)
count+= 1
return count
# Program to test function countSetBits
i = 9
print(countSetBits(i))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to Count set
// bits in an integer
using System;
class GFG {
/* Function to get no of set
bits in binary representation
of passed binary no. */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// Driver Code
static public void Main()
{
int i = 9;
Console.WriteLine(countSetBits(i));
}
}
// This code is contributed by ajit
的PHP
Java脚本
输出 :
2
Brian Kernighan算法的示例:
n = 9 (1001)
count = 0
Since 9 > 0, subtract by 1 and do bitwise & with (9-1)
n = 9&8 (1001 & 1000)
n = 8
count = 1
Since 8 > 0, subtract by 1 and do bitwise & with (8-1)
n = 8&7 (1000 & 0111)
n = 0
count = 2
Since n = 0, return count which is 2 now.
时间复杂度: O(logn)
递归方法:
C++
// CPP implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan’s Algorithm
#include
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// driver code
int main()
{
// get value from user
int n = 9;
// function calling
cout << countSetBits(n);
return 0;
}
// This code is contributed by Raj.
Java
// Java implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
import java.io.*;
class GFG {
// recursive function to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// Driver function
public static void main(String[] args)
{
// get value from user
int n = 9;
// function calling
System.out.println(countSetBits(n));
}
}
// This code is contributed by sunnysingh
Python3
# Python3 implementation for
# recursive approach to find
# the number of set bits using
# Brian Kernighan’s Algorithm
# recursive function to count
# set bits
def countSetBits(n):
# base case
if (n == 0):
return 0
else:
return 1 + countSetBits(n & (n - 1))
# Get value from user
n = 9
# function calling
print(countSetBits(n))
# This code is contributed by sunnysingh
C#
// C# implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
using System;
class GFG {
// recursive function
// to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
// Driver Code
static public void Main()
{
// get value from user
int n = 9;
// function calling
Console.WriteLine(countSetBits(n));
}
}
// This code is contributed by aj_36
的PHP
Java脚本
输出 :
2
3.使用查找表:我们可以使用查找表对O(1)时间中的位进行计数。有关详细信息,请参见http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
int BitsSetTable256[256];
// Function to initialise the lookup table
void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) +
BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff] +
BitsSetTable256[(n >> 8) & 0xff] +
BitsSetTable256[(n >> 16) & 0xff] +
BitsSetTable256[n >> 24]);
}
// Driver code
int main()
{
// Initialise the lookup table
initialize();
int n = 9;
cout << countSetBits(n);
}
// This code is contributed by Sanjit_Kumar
Java
// Java implementation of the approach
class GFG {
// Lookup table
static int[] BitsSetTable256 = new int[256];
// Function to initialise the lookup table
public static void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++) {
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}
// Driver code
public static void main(String[] args)
{
// Initialise the lookup table
initialize();
int n = 9;
System.out.print(countSetBits(n));
}
}
Python
# Python implementation of the approach
BitsSetTable256 = [0] * 256
# Function to initialise the lookup table
def initialize():
# To initially generate the
# table algorithmically
BitsSetTable256[0] = 0
for i in range(256):
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2]
# Function to return the count
# of set bits in n
def countSetBits(n):
return (BitsSetTable256[n & 0xff] +
BitsSetTable256[(n >> 8) & 0xff] +
BitsSetTable256[(n >> 16) & 0xff] +
BitsSetTable256[n >> 24])
# Driver code
# Initialise the lookup table
initialize()
n = 9
print(countSetBits(n))
# This code is contributed by SHUBHAMSINGH10
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Lookup table
static int[] BitsSetTable256 = new int[256];
// Function to initialise the lookup table
public static void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
public static int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff]
+ BitsSetTable256[(n >> 8) & 0xff]
+ BitsSetTable256[(n >> 16) & 0xff]
+ BitsSetTable256[n >> 24]);
}
// Driver code
public static void Main(String[] args)
{
// Initialise the lookup table
initialize();
int n = 9;
Console.Write(countSetBits(n));
}
}
// This code is contributed by 29AjayKumar
Java脚本
2
我们可以在计数要翻转以将A转换为B的位数时找到计数设置位的一种用法
注意:在GCC中,我们可以使用__builtin_popcount()直接计数设置位。因此,我们可以避免使用单独的函数来计数设置位。
C++
// C++ program to demonstrate __builtin_popcount()
#include
using namespace std;
int main()
{
cout << __builtin_popcount(4) << endl;
cout << __builtin_popcount(15);
return 0;
}
Java
// java program to demonstrate
// __builtin_popcount()
import java.io.*;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println(Integer.bitCount(4));
System.out.println(Integer.bitCount(15));
}
}
// This code is contributed by Raj
Python3
# Python3 program to demonstrate __builtin_popcount()
print(bin(4).count('1'));
print(bin(15).count('1'));
# This code is Contributed by mits
C#
// C# program to demonstrate
// __builtin_popcount()
using System;
using System.Linq;
class GFG {
// Driver code
public static void Main()
{
Console.WriteLine(Convert.ToString(4, 2).Count(c = > c == '1'));
Console.WriteLine(Convert.ToString(15, 2).Count(c = > c == '1'));
}
}
// This code is contributed by mits
的PHP
输出 :
1
4
4.用该位映射数字。它只是维护数字到位的映射(或数组),以进行半字节。半字节包含4位。因此,我们需要最多15个数组。
int num_to_bits [16] = {0,1,1,2,1,2,2,2,3,1,2,2,3,2,3,3,4};
现在我们只需要递归地得到给定的long / int / word等字节。
C++
// C++ program to count set bits by pre-storing
// count set bits in nibbles.
#include
using namespace std;
int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
unsigned int countSetBitsRec(unsigned int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
int main()
{
int num = 31;
cout << countSetBitsRec(num);
return 0;
}
// This code is contributed by rathbhupendra
C
// C program to count set bits by pre-storing
// count set bits in nibbles.
#include
int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
unsigned int countSetBitsRec(unsigned int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
int main()
{
int num = 31;
printf("%d\n", countSetBitsRec(num));
}
Java
// Java program to count set bits by pre-storing
// count set bits in nibbles.
class GFG {
static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2,
3, 1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
static int countSetBitsRec(int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
public static void main(String[] args)
{
int num = 31;
System.out.println(countSetBitsRec(num));
}
}
// this code is contributed by mits
Python3
# Python3 program to count set bits by pre-storing
# count set bits in nibbles.
num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
# Recursively get nibble of a given number
# and map them in the array
def countSetBitsRec(num):
nibble = 0;
if(0 == num):
return num_to_bits[0];
# Find last nibble
nibble = num & 0xf;
# Use pre-stored values to find count
# in last nibble plus recursively add
# remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
# Driver code
num = 31;
print(countSetBitsRec(num));
# this code is contributed by mits
C#
// C# program to count set bits by pre-storing
// count set bits in nibbles.
class GFG {
static int[] num_to_bits = new int[16] { 0, 1, 1, 2, 1, 2, 2,
3, 1, 2, 2, 3, 2, 3, 3, 4 };
/* Recursively get nibble of a given number
and map them in the array */
static int countSetBitsRec(int num)
{
int nibble = 0;
if (0 == num)
return num_to_bits[0];
// Find last nibble
nibble = num & 0xf;
// Use pre-stored values to find count
// in last nibble plus recursively add
// remaining nibbles.
return num_to_bits[nibble] + countSetBitsRec(num >> 4);
}
// Driver code
static void Main()
{
int num = 31;
System.Console.WriteLine(countSetBitsRec(num));
}
}
// this code is contributed by mits
的PHP
> 4);
}
// Driver code
$num = 31;
echo (countSetBitsRec($num));
// This code is contributed by mits
?>
输出 :
5
时间复杂度: O(1)
存储复杂度: O(1)无论给定的数字是short,int,long还是long long,我们只需要16个大小恒定的数组即可。
5.检查数字中的每一位:
检查数字中的每个位是否已设置。该数字是按位与的,且具有2的幂,因此,如果结果不等于0,我们就会知道该位置中的特定位已设置。
C
#include
// Check each bit in a number is set or not
// and return the total count of the set bits.
int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < sizeof(int) * 8; i++) {
if (N & (1 << i))
count++;
}
return count;
}
// Driver Code
int main()
{
int N = 15;
printf("%d", countSetBits(N));
return 0;
}
C++
#include
using namespace std;
// Check each bit in a number is set or not
// and return the total count of the set bits.
int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < sizeof(int) * 8; i++) {
if (N & (1 << i))
count++;
}
return count;
}
int main()
{
int N = 15;
cout << countSetBits(N) << endl;
return 0;
}
Java
public class GFG
{
// Check each bit in a number is set or not
// and return the total count of the set bits.
static int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < 4 * 8; i++)
{
if ((N & (1 << i)) != 0)
count++;
}
return count;
}
// Driver code
public static void main(String[] args)
{
int N = 15;
System.out.println(countSetBits(N));
}
}
// This code is contributed by divyeshrabadiya07.
Python3
# Check each bit in a number is set or not
# and return the total count of the set bits
def countSetBits(N):
count = 0
# (1 << i) = pow(2, i)
for i in range(4*8):
if(N & (1 << i)):
count += 1
return count
# Driver code
N = 15
print(countSetBits(N))
# This code is contributed by avanitrachhadiya2155
C#
using System;
class GFG
{
// Check each bit in a number is set or not
// and return the total count of the set bits.
static int countSetBits(int N)
{
int count = 0;
// (1 << i) = pow(2, i)
for (int i = 0; i < 4 * 8; i++)
{
if ((N & (1 << i)) != 0)
count++;
}
return count;
}
// Driver code
static void Main()
{
int N = 15;
Console.WriteLine(countSetBits(N));
}
}
// This code is contributed by divyesh072019.
Java脚本
4
使用查找表对整数中的设置位进行计数
参考:
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive