Absolute difference between set and unset bit count in N

Prerequisite: Bitset function in STL library
Given a number N, the task is to find the absolute difference of the number of set and unset bits of this given number.

Examples:

Input: N = 14
Output: 2
Explanation:
Binary representation of 14 is “1110”.
Here the number of set bits is 3 and the number of unset bits is 1.
Therefore, the absolute difference is 2.

Input: N = 56
Output: 0
Explaination:
Binary representation of 56 is “110100”.
Here the number of set bits is 3 and the number of unset bits is 3.
Therefore, the absolute difference 0.

Approach:



  1. Count the total number of bits in the binary representation of the given number.
  2. Use bitset function defined in the STL library, to count the number of set bits efficiently.
  3. Then, we will subtract the set bits from the total number of bits to get the number of unset bits.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Max size of bitset
const int sz = 64;
  
// Function to return the total bits
// in the binary representation
// of a number
int totalbits(int N)
{
    return (int)(1 + log2(N));
}
  
// Function to calculate the
// absolute difference
int absoluteDifference(int N)
{
    bitset<sz> arr(N);
  
    int total_bits = totalbits(N);
  
    // Calculate the number of
    // set bits
    int set_bits = arr.count();
  
    // Calculate the number of
    // unset bits
    int unset_bits = total_bits
                     - set_bits;
  
    int ans = abs(set_bits
                  - unset_bits);
  
    // Return the absolute difference
    return ans;
}
  
// Driver Code
int main()
{
    // Given Number
    int N = 14;
  
    // Function Call
    cout << absoluteDifference(N);
    return 0;
}

chevron_right


Output:

2

Time Complexity: O(log N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : beast_sr