Skip to content

Commit f73b859

Browse files
added xor queries solution
1 parent 2ce2c86 commit f73b859

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

leetcode/array/xorQueries.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Q2. XOR QUERIES - II
2+
3+
// Given three integers A, B and C.
4+
// Return the maximum possible value of A ^ D, such that D is an integer in range [B, C].
5+
// Note 1: ^ repersents BITWISE xor.
6+
// Note 2: A single testfile may contain multiple testcases upto 105.
7+
8+
9+
// Problem Constraints
10+
// 1 <= A, B, C <= 109
11+
12+
13+
// Input Format
14+
// The first argument given is the integer A.
15+
// The second argument given is the integer B.
16+
// The third argument given is the integer C.
17+
18+
19+
// Output Format
20+
// Return the maximum possible value of A ^ D, such that D is an integar in range [B, C].
21+
22+
23+
// Example Input
24+
// Input 1:
25+
// A = 2
26+
// B = 1
27+
// C = 10
28+
// Input 2:
29+
// A = 3
30+
// B = 5
31+
// C = 6
32+
33+
34+
// Example Output
35+
// Output 1:
36+
// 11
37+
// Output 2:
38+
// 6
39+
40+
41+
// Example Explanation
42+
// Explanation 1:
43+
// For D = 9, A ^ D = 11, which is maximum for any D in range [1, 10].
44+
// Explanation 2:
45+
// For D = 5, A ^ D = 6, which is maximum for any D in range [5, 6]
46+
47+
int Solution::solve(int A, int B, int C){
48+
int x=0;
49+
for(int i=30;i>=0;i--)
50+
{
51+
int q=1<<i;
52+
bool a=A&q;
53+
if(a==1)
54+
{
55+
if(x+q-1>=B);
56+
else
57+
{
58+
x=x+q;
59+
}
60+
61+
}
62+
else
63+
{
64+
if(x+q<=C)x=x+q;
65+
66+
}
67+
// cout<<q<<" "<<x<<endl;
68+
69+
70+
71+
}
72+
return x^A;
73+
74+
}

0 commit comments

Comments
 (0)