VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-smaller-numbers-whose-xor-n-produces-greater-value/

⇱ Count smaller numbers whose XOR with n produces greater value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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. 
 

Output: 

4


Time complexity: O(logn)

Auxiliary Space: O(1)


 

Comment
Article Tags: