Generate original Array from the bitwise AND and Bitwise OR of adjacent elements
Given an integer N denoting the size of an array and two arrays containing Bitwise AND and Bitwise OR of adjacent elements of the array and the first element of the array X, the task is to build the original array.
Examples:
Input: N = 2, X(First element) = 2
Bitwise OR = {3}, Bitwise AND = {2}
Output: {2, 3}
Input: N = 3, X(First element) = 3
Bitwise OR = {4, 3}, Bitwise AND = {3, 4}
Output: {3, 4, 3}
Approach: To solve the problem follow the below idea:
The problem can be solved using this mathematical relation -> A|B = A + B – A&B
Follow the given steps to solve the problem:
- Iterate from i = 1 to N-1 to calculate the remaining array elements.
- Use the formula stated above to generate array values
- Then print all elements
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > solve( int N, int X, int OR[], int AND[])
{
vector< int > a(N);
a[0] = X;
for ( int i = 1; i < N; i++) {
a[i] = OR[i - 1] + AND[i - 1] - a[i - 1];
}
return a;
}
int main()
{
int N = 2, X = 2;
int OR[] = { 3 };
int AND[] = { 2 };
vector< int > ans = solve(N, X, OR, AND);
for ( int i : ans)
cout << i << " " ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int [] solve( int N, int X, int [] OR, int [] AND)
{
int [] a = new int [N];
a[ 0 ] = X;
for ( int i = 1 ; i < N; i++) {
a[i] = OR[i - 1 ] + AND[i - 1 ] - a[i - 1 ];
}
return a;
}
public static void main(String[] args)
{
int N = 2 , X = 2 ;
int [] OR = { 3 };
int [] AND = { 2 };
int [] ans = solve(N, X, OR, AND);
for ( int i = 0 ; i < ans.length; i++) {
System.out.print(ans[i] + " " );
}
}
}
|
Python3
def solve(N, X, OR, AND) :
a = [ None ] * N
a[ 0 ] = X
for i in range ( 1 ,N) :
a[i] = OR[i - 1 ] + AND[i - 1 ] - a[i - 1 ]
return a
if __name__ = = "__main__" :
N, X = 2 , 2
OR = [ 3 ]
AND = [ 2 ]
ans = solve(N, X, OR, AND)
for i in ans :
print (i,end = ' ' )
|
C#
using System;
class GFG {
static int [] solve( int N, int X, int [] OR, int [] AND)
{
int [] a = new int [N];
a[0] = X;
for ( int i = 1; i < N; i++) {
a[i] = OR[i - 1] + AND[i - 1] - a[i - 1];
}
return a;
}
public static void Main()
{
int N = 2, X = 2;
int [] OR = { 3 };
int [] AND = { 2 };
int [] ans = solve(N, X, OR, AND);
for ( int i = 0; i < ans.Length; i++) {
Console.Write(ans[i] + " " );
}
}
}
|
Javascript
<script>
const solve = (N, X, OR, AND) => {
let a = new Array(N).fill(0);
a[0] = X;
for (let i = 1; i < N; i++) {
a[i] = OR[i - 1] + AND[i - 1] - a[i - 1];
}
return a;
}
let N = 2, X = 2;
let OR = [3];
let AND = [2];
let ans = solve(N, X, OR, AND);
for (let i in ans)
document.write(`${ans[i]} `);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
03 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...