forked from Lakhankumawat/LearnCPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximizeExpression.cpp
44 lines (33 loc) Β· 925 Bytes
/
MaximizeExpression.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
//https://www.geeksforgeeks.org/maximize-the-expression-bit-manipulation/
#define MAX 32
// Function to return the value of the maximized expression
int maximizingTheExpression(int x, int y)
{
int ans = x;
// int can have 32 bits
for (int bit = MAX - 1; bit >= 0; bit--) {
// Considering the ith bit of W to be 1
int bitOfW = 1 << bit;
// Calculating the value of (y AND bitOfW)
int a = y & bitOfW;
// Checking if bitOfD satisfies (y AND W = W)
if (a == bitOfW) {
// Checking if bitOfD can maximize (x ^ W)
int b = ans & bitOfW;
if (b == 0) {
ans = ans ^ bitOfW;
}
}
}
return ans;
}
int main()
{
int x, y;
cout<<"Enter the value of x and y ";
cin>>x>>y;
cout << maximizingTheExpression(x,y);
return 0;
}