Check if a number has same number of set and unset bits
Given a number N, the task is to check whether the count of the set and unset bits in the given number are same.
Examples:
Input: 12
Output: Yes
1100 is the binary representation of 12
which has 2 set and 2 unset bits
Input: 14
Output: No
Approach: Traverse in the binary representation of the given number, check if the leftmost bit is set or not using n & 1. If n & 1 returns 1, then the left most bit is set. Right, shift the number every time by 1 to check the next bit. Once the binary representation is traversed completely, check if the number of set bit and unset bits are same. If they are same, print “YES” else print “NO”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkSame( int n)
{
int set = 0, unset = 0;
while (n) {
if (n & 1)
set++;
else
unset++;
n = n >> 1;
}
if (set == unset)
return true ;
else
return false ;
}
int main()
{
int n = 12;
if (checkSame(n))
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean checkSame( int n)
{
int set = 0 ;
int unset = 0 ;
while (n > 0 )
{
if ((n & 1 ) == 1 )
set++;
else
unset++;
n = n >> 1 ;
}
if (set == unset)
return true ;
else
return false ;
}
public static void main (String[] args)
{
int n = 12 ;
if (checkSame(n))
System.out.println ( "YES" );
else
System.out.println( "NO" );
}
}
|
Python3
def checkSame(n):
set , unset = 0 , 0
while (n):
if (n and 1 ):
set + 1
else :
unset + = 1
n = n >> 1
if ( set = = unset):
return True
else :
return False
if __name__ = = '__main__' :
n = 12
if (checkSame(n)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG{
static bool checkSame( int n)
{
int set = 0;
int unset = 0;
while (n > 0)
{
if ((n & 1) == 1)
set ++;
else
unset++;
n = n >> 1;
}
if ( set == unset)
return true ;
else
return false ;
}
static public void Main (){
int n = 12;
if (checkSame(n))
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
}
|
PHP
<?php
function checkSame( $n )
{
$set = 0;
$unset = 0;
while ( $n )
{
if ( $n & 1)
$set ++;
else
$unset ++;
$n = $n >> 1;
}
if ( $set == $unset )
return true;
else
return false;
}
$n = 12;
if (checkSame( $n ))
echo "YES" ;
else
echo "NO" ;
?>
|
Javascript
<script>
function checkSame( n)
{
let set = 0, unset = 0;
while (n) {
if (n & 1)
set++;
else
unset++;
n = n >> 1;
}
if (set == unset)
return true ;
else
return false ;
}
let n = 12;
if (checkSame(n))
document.write( "YES" );
else
document.write( "NO" );
</script>
|
Time complexity: O(logn)
Auxiliary space: O(1)
Last Updated :
21 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...