Count smaller numbers whose XOR with n produces greater value

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 C++ implementation of the above idea.

// C++ program to count numbers whose XOR with n
// produces a value more than n.
#include<bits/stdc++.h>
using namespace std;

int countNumbers(int n)
{
    /* If there is a number like m = 11110000,
    then it is bigger then 1110xxxx. x can either
    0 or 1. So we have pow(2, k) greater numbers
    where k is  position of rightmost 1 in m. Now
    by using XOR bit at each  position can be changed.
    To change bit at any position, it needs to XOR
    it with 1. */
    int k = 0; // Position of current bit in n

    /* Traverse bits from LSB (least significant bit)
       to MSB */
    int count = 0;  // Initialize result
    while (n > 0)
    {
        // If current bit is 0, then there are
        // 2^k numbers with current bit 1 and
        // whose XOR with n produces greater value
        if ((n&1) == 0)
            count += pow(2, k);

        // Increase position for next bit
        k += 1;

        // Reduce n to find next bit
        n >>= 1;
    }

    return count;
}

// Driver code
int main()
{
    int n = 11;
    cout << countNumbers(n) << endl;
    return 0;
}

Output:

4

Time complexity : O(Log n)

This article is contributed by Smarak Chopdar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.