
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
A | B | A XOR B |
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
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
#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