Count numbers whose XOR with N is equal to OR with N
Last Updated :
21 Aug, 2022
Given a number N, the task is to find the count of X such that N XOR X == N OR X, where 0<=X<=N
Examples:
Input: N = 5
Output: 2
For N = 5,
5 XOR 2 == 5 OR 2
5 XOR 0 == 5 OR 0
Thus, count is 2.
Input: N = 7
Output: 1
For N = 7,
7 XOR 0 == 7 OR 0
Thus, count is 1.
Approach: The idea is to convert a given number to binary and then count the unset bits in it. 2^count gives us the number of X such that N XOR X == N OR X.
Below is the implementation of the above approach:
C++
#include<iostream>
#include<math.h>
using namespace std;
class gfg {
public :
int xorEqualsOrCount( int N)
{
int count = 0;
int bit;
while (N > 0) {
bit = N % 2;
if (bit == 0)
count++;
N = N / 2;
}
return ( int ) pow (2, count);
} };
int main()
{
gfg g ;
int N = 7;
cout<<g.xorEqualsOrCount(N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int xorEqualsOrCount( int N)
{
int count = 0 ;
int bit;
while (N > 0 ) {
bit = N % 2 ;
if (bit == 0 )
count++;
N = N / 2 ;
}
return ( int )Math.pow( 2 , count);
}
public static void main(String args[])
{
int N = 7 ;
System.out.println(xorEqualsOrCount(N));
}
}
|
Python3
def xorEqualsOrCount(N) :
count = 0
while (N > 0 ) :
bit = N % 2
if bit = = 0 :
count + = 1
N / / = 2
return int ( pow ( 2 , count))
if __name__ = = "__main__" :
N = 7
print (xorEqualsOrCount(N))
|
C#
using System;
class GFG {
static int xorEqualsOrCount( int N)
{
int count = 0;
int bit;
while (N > 0) {
bit = N % 2;
if (bit == 0)
count++;
N = N / 2;
}
return ( int )Math.Pow(2, count);
}
public static void Main()
{
int N = 7;
Console.WriteLine(xorEqualsOrCount(N));
}
}
|
PHP
<?php
function xorEqualsOrCount( $N )
{
$count = 0;
while ( $N > 0)
{
$bit = $N % 2;
if ( $bit == 0)
$count ++;
$N = intval ( $N / 2);
}
return pow(2, $count );
}
$N = 7;
echo xorEqualsOrCount( $N );
?>
|
Javascript
<script>
function xorEqualsOrCount(N)
{
let count = 0;
let bit;
while (N > 0) {
bit = N % 2;
if (bit == 0)
count++;
N = parseInt(N / 2);
}
return Math.pow(2, count);
}
let N = 7;
document.write(xorEqualsOrCount(N));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...