Problem Statement:
Given a number N, you need to check if the count of set and unset bits are same.
Example:
Input: 12
Output: Yes
1100 in binary of 12.
Hence true.
Solution Explanation:
Traverse the binary representation of the number.
Check of the leftmost bit is set or not.
Then right shift the number. Once the binary is traversed, count the set and unset bit count and return the result.
Time Complexity: O(logn)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool solution(int n)
{
int set_count = 0, unset_count = 0;
while (n) {
if (n & 1)
set_count++;
else
unset_count++;
n = n >> 1;
}
if (set_count == unset_count)
return true;
else
return false;
}
int main()
{
int n = 3;
if (solution(n))
cout << "Yes" << endl;
else
cout << "No";
return 0;
}
Output
No