Count smaller numbers whose XOR with n produces greater value
Last Updated :
21 Jul, 2022
Given a positive integer n, count numbers x such that 0 < x <n and x^n > n where ^ is bitwise XOR operation.
Examples:
Input : n = 12
Output : 3
Numbers are 1, 2 and 3
1^12 > 12, 2^12 > 12 and 3^12 > 12
Input : n = 11
Output : 4
Numbers are 4, 5, 6 and 7
A number may x produce a greater XOR value if x has a set bit at a position where n has a 0 bit. So we traverse bits of n, and one by one consider all 0 bits. For every set bit at position k (Considering k = 0 for rightmost bit, k = 1 for second rightmost bit, ..), we add 2 2k to result. For a bit at k-th position, there are 2k numbers with set bit 1.
Below is the implementation of the above idea.
C++
#include<bits/stdc++.h>
using namespace std;
int countNumbers( int n)
{
int k = 0;
int count = 0;
while (n > 0)
{
if ((n&1) == 0)
count += pow (2, k);
k += 1;
n >>= 1;
}
return count;
}
int main()
{
int n = 11;
cout << countNumbers(n) << endl;
return 0;
}
|
Java
import java.lang.*;
class GFG {
static int countNumbers( int n)
{
int k = 0 ;
int count = 0 ;
while (n > 0 ) {
if ((n & 1 ) == 0 )
count += ( int )(Math.pow( 2 , k));
k += 1 ;
n >>= 1 ;
}
return count;
}
public static void main(String[] args)
{
int n = 11 ;
System.out.println(countNumbers(n));
}
}
|
Python3
def countNumbers(n):
k = 0
count = 0
while (n > 0 ):
if ((n & 1 ) = = 0 ):
count + = pow ( 2 , k)
k + = 1
n >> = 1
return count
n = 11
print (countNumbers(n))
|
C#
using System;
class GFG {
static int countNumbers( int n)
{
int k = 0;
int count = 0;
while (n > 0) {
if ((n & 1) == 0)
count += ( int )(Math.Pow(2, k));
k += 1;
n >>= 1;
}
return count;
}
public static void Main()
{
int n = 11;
Console.WriteLine(countNumbers(n));
}
}
|
PHP
<?php
function countNumbers( $n )
{
$k = 0;
$count = 0;
while ( $n > 0)
{
if (( $n & 1) == 0)
$count += pow(2, $k );
$k += 1;
$n >>= 1;
}
return $count ;
}
$n = 11;
echo countNumbers( $n );
?>
|
Javascript
<script>
function countNumbers(n)
{
let k = 0;
let count = 0;
while (n > 0) {
if ((n & 1) == 0)
count += (Math.pow(2, k));
k += 1;
n >>= 1;
}
return count;
}
let n = 11;
document.write(countNumbers(n));
</script>
|
Output:
4
Time complexity: O(logn)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...