The Wayback Machine - https://web.archive.org/web/20240828144825/https://www.geeksforgeeks.org/c-program-to-count-zeros-and-ones-in-binary-representation-of-a-number/
Open In App

C program to count zeros and ones in binary representation of a number

Last Updated : 22 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
35.77%
1.8L

Given a number N, the task is to write C program to count the number of 0s and 1s in the binary representation of N.

Examples:  

Input: N = 5 
Output: 
Count of 0s: 1 
Count of 1s: 2 
Explanation: Binary representation of 5 is “101”.
Input: N = 22 
Output: 
Count of 0s: 2 
Count of 1s: 3 
Explanation: Binary representation of 22 is “10110”. 

Method 1 – Naive Approach: The idea is to iterate through all bits in the binary representation of N and increment the count of 0s if current bit is ‘0’ else increment the count of 1s.

Below is the implementation of the above approach:

C




// C program for the above approach
#include <stdio.h>
 
// Function to count the number of 0s
// and 1s in binary representation of N
void count1s0s(int N)
{
    // Initialise count variables
    int count0 = 0, count1 = 0;
 
    // Iterate through all the bits
    while (N > 0) {
 
        // If current bit is 1
        if (N & 1) {
            count1++;
        }
 
        // If current bit is 0
        else {
            count0++;
        }
 
        N = N >> 1;
    }
 
    // Print the count
    printf("Count of 0s in N is %d\n", count0);
    printf("Count of 1s in N is %d\n", count1);
}
 
// Driver Code
int main()
{
    // Given Number
    int N = 9;
 
    // Function Call
    count1s0s(N);
    return 0;
}


Output

Count of 0s in N is 2
Count of 1s in N is 2

Time Complexity: O(log N)
Auxiliary Space: O(1) 

Method 2 – Recursive Approach: The above approach can also be implemented using Recursion. 

Below is the implementation of the above approach:

C




// C program for the above approach
#include <math.h>
#include <stdio.h>
 
// Recursive approach to find the
// number of set bit in 1
int recursiveCount(int N)
{
 
    // Base Case
    if (N == 0) {
        return 0;
    }
 
    // Return recursively
    return (N & 1) + recursiveCount(N >> 1);
}
 
// Function to find 1s complement
int onesComplement(int n)
{
    // Find number of bits in the
    // given integer
    int N = floor(log2(n)) + 1;
 
    // XOR the given integer with
    // pow(2, N) - 1
    return ((1 << N) - 1) ^ n;
}
 
// Function to count the number of 0s
// and 1s in binary representation of N
void count1s0s(int N)
{
    // Initialise the count variables
    int count0, count1;
 
    // Function call to find the number
    // of set bits in N
    count1 = recursiveCount(N);
 
    // Function call to find 1s complement
    N = onesComplement(N);
 
    // Function call to find the number
    // of set bits in 1s complement of N
    count0 = recursiveCount(N);
 
    // Print the count
    printf("Count of 0s in N is %d\n", count0);
    printf("Count of 1s in N is %d\n", count1);
}
 
// Driver Code
int main()
{
    // Given Number
    int N = 5;
 
    // Function Call
    count1s0s(N);
    return 0;
}


Output

Count of 0s in N is 1
Count of 1s in N is 2

Time Complexity: O(log N)
Auxiliary Space: O(1) 

Method 3 – Using Brian Kernighan’s Algorithm 
We can find the count of set bits using the steps below: 

  • Initialise count to 0.
  • If N > 0, then update N as N & (N – 1) as this will unset the most set bit from the right as shown below:
if N = 10;
Binary representation of N     = 1010
Binary representation of N - 1 = 1001
-------------------------------------
Logical AND of N and N - 1     = 1000
  • Increment the count for the above steps and repeat the above steps until N becomes 0.

To find the count of 0s in the binary representation of N, find the one’s complement of N and find the count of set bits using the approach discussed above.

Below is the implementation of the above approach: 

C




// C program for the above approach
#include <math.h>
#include <stdio.h>
 
// Function to find 1s complement
int onesComplement(int n)
{
    // Find number of bits in the
    // given integer
    int N = floor(log2(n)) + 1;
 
    // XOR the given integer with
    // pow(2, N) - 1
    return ((1 << N) - 1) ^ n;
}
 
// Function to implement count of
// set bits using Brian Kernighan’s
// Algorithm
int countSetBits(int n)
{
    // Initialise count
    int count = 0;
 
    // Iterate until n is 0
    while (n) {
        n &= (n - 1);
        count++;
    }
 
    // Return the final count
    return count;
}
 
// Function to count the number of 0s
// and 1s in binary representation of N
void count1s0s(int N)
{
    // Initialise the count variables
    int count0, count1;
 
    // Function call to find the number
    // of set bits in N
    count1 = countSetBits(N);
 
    // Function call to find 1s complement
    N = onesComplement(N);
 
    // Function call to find the number
    // of set bits in 1s complement of N
    count0 = countSetBits(N);
 
    // Print the count
    printf("Count of 0s in N is %d\n", count0);
    printf("Count of 1s in N is %d\n", count1);
}
 
// Driver Code
int main()
{
    // Given Number
    int N = 5;
 
    // Function Call
    count1s0s(N);
    return 0;
}


Output

Count of 0s in N is 1
Count of 1s in N is 2

Time Complexity: O(log N)
Auxiliary Space: O(1)



Similar Reads

Count number of trailing zeros in Binary representation of a number using Bitset
Given a number. The task is to count the number of Trailing Zero in Binary representation of a number using bitset. Examples: Input : N = 16Output : 4Binary representation of N is 10000. Therefore,number of zeroes at the end is 4.Input : N = 8Output : 3Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach:
5 min read
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
Given a binary string of 0s and 1s. The task is to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string. That is maximize ( number of 0s - number of 1s ) for any sub-string in the given binary string. Examples: Input : S = "11000010001" Output : 6 From index 2 to index 9, there are 7 0s
7 min read
Maximum difference of zeros and ones in binary string
Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s - number of 1s). In case of all 1s print -1. Examples: Input : S = "11000010001"Output : 6From index 2 to index 9, there are 70s and 1 1s, so number of 0s - numberof 1s
15 min read
Make all Ones together by Shifting Ones.
Given, a binary string contains zeroes and ones. In one operation you can move one step character '1' to either left or right. Find the minimum number of operations required to make all ones together without any intermediate zeroes. Examples: Input: 11011Output: 2Explanation: In the first operation move '1' at index 3 to index 2. Now the string bec
6 min read
Maximum number of strings that can be formed with given zeros and ones
Given a list of strings arr[] of zeros and ones only and two integer N and M, where N is the number of 1's and M is the number of 0's. The task is to find the maximum number of strings from the given list of strings that can be constructed with given number of 0's and 1's. Examples: Input: arr[] = {"10", "0001", "11100", "1", "0"}, M = 5, N = 3 Out
15+ min read
Number of leading zeros in binary representation of a given number
Given a positive integer N, the task is to find the number of leading zeros in its binary representation.A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form. Examples: Input : N = 16Output : 27Explanation: As Binary(16) = (00000000000000000000000000010000) Input : N = 33Output : 26Explanation: As Binary
10 min read
Move all zeros to start and ones to end in an Array of random integers
Given an array arr[] of random integers, the task is to push all the zero's in the array to the start and all the one's to the end of the array. Note that the order of all the other elements should be the same.Example: Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0} Output: 0 0 0 2 4 3 5 1 Input: arr[] = {1, 2, 0, 0, 0, 3, 6}; Output: 0 0 0 2 3 6 1 Approac
10 min read
Count of non-consecutive Ones in Binary range
Given two positive integers 'L' and 'R', the task is to return the number of the integers in the range [L, R] inclusive, whose binary representations do not contain consecutive ones where 0 ≤ l ≤ r ≤ 10^9 Examples: Input: L = 0, R = 3Output: 3Explanation: The 3 numbers are 0(00), 1(01), 2(10) 3(11) is not included as its binary representation conta
11 min read
Count of substrings of a binary string containing K ones
Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = “10010” K = 1 Output : 9 The 9 substrings containing one 1 are, “1”, “10”, “100”, “001”, “01”, “1”, “10”, “0010” and “010”Recommended PracticeCount of substrings containing K onesT
7 min read
Count ways to split a Binary String into three substrings having equal count of zeros
Given binary string str, the task is to count the total number of ways to split the given string into three non-overlapping substrings having the same number of 0s. Examples: Input: str = "01010" Output: 4 Explanation: The possible splits are: [0, 10, 10], [01, 01, 0], [01, 0, 10], [0, 101, 0] Input: str = "11111" Output: 0 Approach: To solve the p
15+ min read
Maximum Number of Ones in Binary Matrix
Given a binary matrix mat[][] with dimensions m * n, and any square sub-matrix of mat of size len * len has at most k ones. The task is to return the maximum possible number of ones that the matrix mat can have. Example: Input: m = 3, n = 3, len = 2, k = 1Output: 4Explanation: In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. The best so
8 min read
Difference between 1's Complement representation and 2's Complement representation Technique
Prerequisite - Representation of Negative Binary Numbers 1's complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0. Examples: Let numbers be stored using 4 bits 1's complement of 7 (0111) is 8 (1000) 1's complement of 12 (1100) is 3 (0011) 2's complement of a
3 min read
C Program to count the number of zeros from 0 to N
Given a number N, the task is to write C program to count the number of zeros from 0 to N. Examples: Input: N = 10 Output: 2 Explanation: The number with zeros are 0, 10 till 10. Hence the count of zeros is 2. Input: N = 20 Output: 3 Explanation: The number with zeros are 0, 10, 20 till 20. Hence the count of zeros is 3. Approach: Iterate from 0 to
2 min read
Length of longest consecutive ones by at most one swap in a Binary String
Given a Binary String of length [Tex]N [/Tex]. It is allowed to do at most one swap between any 0 and 1. The task is to find the length of the longest consecutive 1's that can be achieved. Examples: Input : str = "111011101" Output : 7 We can swap 0 at 4th with 1 at 10th position Input : str = "111000" Output : 3 We cannot obtain more than 3 1's af
9 min read
Check if all rows of a Binary Matrix have all ones placed adjacently or not
Given a binary matrix mat[][] of dimension N*M, the task is to check if all 1s in each row are placed adjacently on the given matrix. If all 1s in each row are adjacent, then print "Yes". Otherwise, print "No". Examples: Input: mat[][] = {{0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 0, 1}, {1, 1, 1, 0}Output: YesExplanation:Elements in the first row are {0,
9 min read
Find size of the largest '+' formed by all ones in a binary matrix
Given a N X N binary matrix, find the size of the largest '+' formed by all 1s. Example: For above matrix, largest '+' would be formed by highlighted part of size 17. The idea is to maintain four auxiliary matrices left[][], right[][], top[][], bottom[][] to store consecutive 1’s in every direction. For each cell (i, j) in the input matrix, we stor
15+ min read
Count binary strings with twice zeros in first half
We are given an integer N. We need to count the total number of such binary strings of length N such that the number of '0's in the first string of length N/2 is double of the number of '0's in the second string of length N/2. Note: N is always an even positive integer. Examples: Input : N = 4 Output : 2 Explanation: 0010 and 0001 are two binary st
7 min read
Count of N-bit binary numbers without leading zeros
Given an integer N, the task is to find the count of N-bit binary numbers without leading zeros.Examples: Input: N = 2 Output: 2 10 and 11 are the only possible binary numbers.Input: N = 4 Output: 8 Approach: Since the numbers cannot have leading zeros so the left-most bit has to be set to 1. Now for the rest of the N - 1 bits, there are two choice
2 min read
Count trailing zeroes present in binary representation of a given number using XOR
Given an integer N, the task is to find the number of trailing zeroes in the binary representation of the given number. Examples: Input: N = 12Output: 2Explanation:The binary representation of the number 13 is "1100".Therefore, there are two trailing zeros in the 12. Input: N = -56Output: 3Explanation:The binary representation of the number -56 is
4 min read
Check if the binary representation of a number has equal number of 0s and 1s in blocks
Given an integer N, the task is to check if its equivalent binary number has an equal frequency of consecutive blocks of 0 and 1. Note that 0 and a number with all 1s are not considered to have a number of blocks of 0s and 1s. Examples: Input: N = 5 Output: Yes Equivalent binary number of 5 is 101. The first block is of 1 with length 1, the second
10 min read
Binary representation of next greater number with same number of 1's and 0's
Given a binary input that represents binary representation of positive number n, find binary representation of smallest number greater than n with same number of 1's and 0's as in binary representation of n. If no such number can be formed, print "no greater number".The binary input may be and may not fit even in unsigned long long int. Examples: I
12 min read
Count of Non-Negative Integers that doesn't contain consecutive ones
Given a range of integers, the task is to find the numbers of Non-Negative Integers which doesn't contain consecutive ones (1s) in their binary representation. Examples: Input: [0, 7]Output: 5 Input: [0, 10]Output: 8 Input: [2, 10]Output: 6 Approach: This code uses the following approach to find the number of non-negative integers in the given rang
6 min read
Queries to answer the number of ones and zero to the left of given index
Given a binary array and Q queries. Every query consists of a number K, the task is to print the number of ones and zeros to the left of the index K. Examples: Input: arr[] = {1, 1, 1, 0, 0, 1, 0, 1, 1}, Q[] = {0, 1, 2, 4} Output: 0 ones 0 zeros 1 ones 0 zeros 2 ones 0 zeros 3 ones 1 zerosInput: arr[] = {1, 0, 1, 0, 1, 1}, Q[] = {2, 3} Output: 1 on
6 min read
Number of ones in the smallest repunit
Given a positive integer N whose unit’s digit is 3. Find the number of 1s in the smallest repunit which is divisible by the given number N. Every number whose unit’s digit is 3 has a repunit as its multiple. A repunit is a number which has only ones. It is of the form (10n – 1)/9.Examples: Input: 3 Output: 3 As 3 divides 111 which is the smallest r
6 min read
Maximum number of ones in a N*N matrix with given constraints
Given two integers [Tex]n [/Tex]and [Tex]x [/Tex], where [Tex]x &lt;= n [/Tex]. Find the maximum number of one's in a [Tex]n * n [/Tex]binary matrix can have such that every sub-matrix of size [Tex]x * x [/Tex]has atleast one cell as zero. Examples: Input:5 3 Output: Maximum number of ones = 24 The matrix will be: 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1
5 min read
Minimize the number of iterations to Fill a Matrix with Ones
Given a matrix with dimensions N x M, filled with zeroes except for one position at coordinates X and Y containing '1'. In one iteration, '1' can be filled in the 4 neighboring elements of a cell containing '1'. This means if there are 2 cells with '1', their neighboring cells can be marked as '1' in the next iteration. Find the minimum number of i
5 min read
Find the occurrence of the given binary pattern in the binary representation of the array elements
Given an array arr[] of N positive integers and a string patt which consists of characters from the set {0, 1}, the task is to find the count occurrence of patt in the binary representation of every integer from the given array. Examples: Input: arr[] = {5, 106, 7, 8}, patt = "10" Output: 1 3 0 1 binary(5) = 101 -&gt; occurrence(10) = 1 binary(106)
9 min read
Count numbers from a given range having same first and last digits in their binary representation
Given two integers L and R, the task is to find the count of numbers in the range [L, R] whose first and last digit in the binary representation are the same. Examples: Input: L = 1, R = 5Output: 3Explanation:(1)10 = (1)2(2)10 = (10)2(3)10 = (11)2(4)10 = (100)2(5)10 = (101)2Therefore, 1, 3, 5 has the same first and last digits in their binary repre
4 min read
Count number of trailing zeros in product of array
Given a array size of n, we need to find the total number of zeros in the product of array. Examples: Input : a[] = {100, 20, 40, 25, 4} Output : 6 Product is 100 * 20 * 40 * 25 * 4 which is 8000000 and has 6 trailing 0s. Input : a[] = {10, 100, 20, 30, 25, 4, 43, 25, 50, 90, 12, 80} Output : 13 A simple solution is simply multiply and count traili
6 min read
Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..
Given an integer n, the task is to find the number of trailing zeros in the function [Tex]f(n)=\prod\limits_{i = 1}^{n} i^{i} [/Tex]i.e. f(n) = 11 * 22 * 33 * ... * nn. Examples: Input: n = 5 Output: 5 f(5) = 11 * 22 * 33 * 44 * 55 = 1 * 4 * 27 * 256 * 3125 = 86400000 Input: n = 12 Output: 15 Approach: We know that 5 * 2 = 10 i.e. 1 trailing zero i
7 min read