
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
Check If a Number from Every Row Can Be Selected for XOR in C++
Suppose we have one 2D array of size N x M. The task is to check if we can select a number from every row, in such a way that the XOR of those elements is non-zero or greater than 0. Suppose one matrix is like this −
7 | 7 | 7 |
10 | 10 | 7 |
If we perform XOR, the answer will be non-zero, as the except last elements of two rows are 7 and 10
To solve this problem, the solution will be very easy. Initially check if XOR of the elements of the first column of each row is 0 or not. If it is non-zero then it is possible. otherwise, check if any of the rows have two or more distinct elements or not, if yes then also it is possible. If both of the above conditions are not satisfied, then it is not possible.
Example
#include<iostream> using namespace std; #define N 2 #define M 3 bool isXORnonZero(int matrix[N][M]) { int xor_value = 0; for (int i = 0; i < N; i++) { xor_value ^= matrix[i][0]; } if (xor_value != 0) return true; for (int i = 0; i < N; i++) { for (int j = 1; j < M; j++) { if (matrix[i][j] != matrix[i][0]) return true; } } return false; } int main() { int mat[N][M] = { { 7, 7, 7 }, { 10, 10, 7 } }; if (isXORnonZero(mat)) cout << "XOR has non-zero value"; else cout << "XOR has zero value"; }
Output
XOR has non-zero value
Advertisements