Count smaller values whose XOR with x is greater than x in C++


We are given an integer number let’s say, x and the task are to count the smaller numbers less than x whose XOR with x 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 x = 11

Output − Count of smaller values whose XOR with x is greater than x are − 4

Explanation

We are given with the x as 11 which means we need to find XOR of x with the numbers less than x. 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 x = 12

Output − Count of smaller values whose XOR with x is greater than x are − 11

Explanation

We are given with the x as 12 which means we need to find XOR of x with the numbers less than x. 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 x.

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

  • Create a temporary variable count to store the result and a variable named num and set it to 1.

  • Start loop WHILE till x != 0

  • Inside the loop, check IF x%2 == 0 then set the count as count + num

  • Set num as num * 2 and x as x / 2

  • Return the count

  • Print the result

Example

 Live Demo

#include
using namespace std;
int XOR_smaller(int x){
   int count = 0;
   int num = 1;
   while (x != 0){
      if (x%2 == 0){
         count = count + num;
      }
      num = num*2;
      x = x/2;
   }
   return count;
}
int main(){
   int x = 20;
   cout<<"Count of smaller values whose XOR with x is greater than x are: "<<XOR_smaller(x);
   return 0;
}

Output

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

Count of smaller values whose XOR with x is greater than x are: 11

Updated on: 31-Aug-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements