The Castle Gate

Gudi, a fun-loving girl from the city of Dun, travels to Azkahar - a strange land beyond the mountains. She arrives at the gates of Castle Grey, owned by Puchi, the lord of Azkahar to claim the treasure that it guards. However, destiny has other plans for her as she has to move through floors, crossing obstacles on her way to reach the treasure.

The gates of the castle are closed. An integer N is engraved on the gates. Writing on the wall says

Tap the gates as many times as there are unordered pairs of distinct integers from 1 to N whose bit-wise XOR does not exceed N.


Help her find the number of times she has to tap.

Example:

Input:  n = 6
Output: 12

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int theCastleGate(int n)
{
    int cnt = 0;
    for (int i = 1i < ni++)
    {
        for (int j = i + 1j <= nj++)
        {
            if ((i ^ j) <= n)
                cnt++;
        }
    }
    return cnt;
}
int main()
{
    int n = 6;

    cout << theCastleGate(n<< "\n";

    return 0;
}


No comments:

Post a Comment