
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a number has same number of set and unset bits in C++
In this section we will check whether a number has same number of set bits and unset bits or not. Suppose the number 12 is there. Its binary representation is 1100. This has same number of 0s and 1s.
The approach is simple. We will check each bit of the number, and if that is 1, then increase set_bit_count, and if it is 0, then increase unset_bit_count. Finally, if they are same, then return true, otherwise false.
Example
#include <iostream> using namespace std; bool hasSameSetUnset(int n) { int set_count = 0, unset_count = 0; while(n){ if((n & 1) == 1){ set_count++; }else{ unset_count++; } n = n >> 1; //shift to right } if(set_count == unset_count) return true; return false; } int main() { int num = 35; //100011 if(hasSameSetUnset(num)){ cout << "Has same set, unset bits"; }else{ cout << "Not same number of set, unset bits"; } }
Output
Has same set, unset bits
- Related Articles
- Check if a number has two adjacent set bits in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Count unset bits of a number in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Find the largest number with n set and m unset bits in C++
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Next higher number with same number of set bits in C++
- Check if all bits of a number are set in Python
- Check whether the number has only first and last bits set in Python
- Maximum number of contiguous array elements with same number of set bits in C++
- Minimum number using set bits of a given number in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Count unset bits in a range in C++
- Program to find higher number with same number of set bits as n in Python?\n

Advertisements