Count smaller numbers whose XOR with n produces greater value in C++


We are given an integer number let’s say, num and the task is to count the smaller numbers less than num whose XOR with num will result in a value greater than the XOR value..

The truth table for XOR operation is given below

ABA XOR B
000
101
011
110

Input − int num = 11

Output − Count of smaller numbers whose XOR with n produces greater value are − 4

Explanation

We are given with the num as 11 which means we need to find XOR of num with the numbers less than num. So the numbers are 1 XOR 11 < 11(FALSE), 2 XOR 11 < 11(FALSE), 3 XOR 11 < 11(FALSE), 4 XOR 11 > 11(TRUE), 5 XOR 11 > 11(TRUE), 6 XOR 11 > 11(TRUE), 7 XOR 11> 11(TRUE), 8 XOR 11< 11(FALSE), 9 XOR 11 < 11(FALSE), 10 XOR 11 < 11(FALSE).

Input − int num = 12

Output − Count of smaller numbers whose XOR with n produces greater value are − 3

Explanation

We are given with the num as 12 which means we need to find XOR of num with the numbers less than num. So the numbers are 1 XOR 12 > 12(TRUE), 2 XOR 12 > 12(TRUE), 3 XOR 12 > 12(TRUE), 4 XOR 12 < 12(FALSE), 5 XOR 12 < 12(FALSE), 6 XOR 12 < 12(FALSE), 7 XOR 12< 12(FALSE), 8 XOR 12< 12(FALSE), 9 XOR 12 < 12(FALSE), 10 XOR 12 < 12(FALSE), 11 XOR 12 < 12(FALSE).

Approach used in the below program is as follows

  • Input an integer element and store it in a variable named num.

  • Pass the value of num to the function for further processing

  • Create a temporary variable count to store the result.

  • Start loop WHILE till num > 0

  • Inside the loop, check IF num & 1 == TRUE then set the count as count + pow(2, temp)

  • Increment the value of temp by 1

  • And set num to num >> = 1

  • Return the count

  • Print the result

Example

 Live Demo

#include
using namespace std;
//Count smaller numbers whose XOR with n produces greater value
int XOR_greater(int n){
   int temp = 0;
   int count = 0;
   while (n > 0){
      if ((n&1) == 0){
         count += pow(2, temp);
      }
      temp++;
      n >>= 1;
   }
   return count;
}
int main(){
   int n = 20;
   cout<<"Count of smaller numbers whose XOR with n produces greater value are: "<<XOR_greater(n) << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of smaller numbers whose XOR with n produces greater value are: 11

Updated on: 31-Aug-2020

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements