Given a positive integer n, count numbers x such that 0 < x <n and x^n > n where ^ is bitwise XOR operation.
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.
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 firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live