Odious number
Last Updated :
15 Jun, 2022
Odious number is a nonnegative number that has an odd number of 1s in its binary expansion. The first few odious numbers are therefore 1, 2, 4, 7, 8, 11, 13, 14, 16, 19…
Given a number check if its a odious number or not.
Examples :
Input : 16
Output : Odious Number
Explanation: Binary expansion of 16 = 10000,
having number of 1s =1 i.e odd.
Input : 23
Output : Not odious number
Explanation: Binary expansion of 23 is 10111,
the number of 1s in this is 4 i.e even.
1) Count set bits in given number.
2) Return true if the count is odd, false otherwise.
C++
#include <iostream>
using namespace std;
#include <math.h>
int countSetBits( int n)
{
unsigned int count = 0;
while (n)
{
n &= (n-1) ;
count++;
}
return count;
}
int checkOdious( int n)
{
return (countSetBits(n) % 2 == 1);
}
int main()
{
int num = 32;
if (checkOdious(num))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.math.*;
class GFG {
static int countSetBits( int n)
{
int count = 0 ;
while (n!= 0 )
{
n &= (n- 1 ) ;
count++;
}
return count;
}
static boolean checkOdious( int n)
{
return (countSetBits(n) % 2 == 1 );
}
public static void main(String args[])
{
int num = 32 ;
if (checkOdious(num))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def countSetBits(n) :
count = 0
while (n) :
n = n & (n - 1 )
count = count + 1
return count
def checkOdious(n) :
return (countSetBits(n) % 2 = = 1 )
num = 32
if (checkOdious(num)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int count = 0;
while (n != 0)
{
n &= (n - 1) ;
count++;
}
return count;
}
static bool checkOdious( int n)
{
return (countSetBits(n) % 2 == 1);
}
public static void Main()
{
int num = 32;
if (checkOdious(num))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
function countSetBits( $n )
{
$count = 0;
while ( $n )
{
$n &= ( $n - 1) ;
$count ++;
}
return $count ;
}
function checkOdious( $n )
{
return (countSetBits( $n ) % 2 == 1);
}
$num = 32;
if (checkOdious( $num ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function countSetBits(n)
{
let count = 0;
while (n!=0)
{
n &= (n-1) ;
count++;
}
return count;
}
function checkOdious(n)
{
return (countSetBits(n) % 2 == 1);
}
let num = 32;
if (checkOdious(num))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output :
Yes
Time Complexity: O(logn)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...