Input: a =12, b =5, n =4 Output:98 Explanation: For x =2,(a XOR x)=14and(b XOR x)=7. Hence,(a XOR x)*(b XOR x)=98. It can be shown that 98is the maximum value of(a XOR x)*(b XOR x)for all 0<= x <2n.
Input: a =6, b =7, n =5 Output:930 Explanation: For x =25,(a XOR x)=31and(b XOR x)=30. Hence,(a XOR x)*(b XOR x)=930. It can be shown that 930is the maximum value of(a XOR x)*(b XOR x)for all 0<= x <2n.
Input: a =1, b =6, n =3 Output:12 Explanation: For x =5,(a XOR x)=4and(b XOR x)=3. Hence,(a XOR x)*(b XOR x)=12. It can be shown that 12is the maximum value of(a XOR x)*(b XOR x)for all 0<= x <2n.
To maximize (a XOR x) * (b XOR x), we want both terms to be as large as possible. Since XOR flips bits, setting bits in x where a and b have zeros can help maximize both terms. The largest possible value for x is 2^n - 1, which sets all n bits to 1.
classSolution {
public:int maximumXorProduct(int a, int b, int n) {
int mod =1e9+7;
int lim = (1<< n) -1;
longlong ans =0;
for (int x =0; x <= lim; ++x) {
longlong cur =1LL* (a ^ x) * (b ^ x);
if (cur > ans) ans = cur;
}
return ans % mod;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcmaximumXorProduct(aint, bint, nint) int {
mod:= int(1e9+7)
lim:= (1<<n) -1ans:=0forx:=0; x<=lim; x++ {
cur:= (a ^ x) * (b ^ x)
ifcur > ans {
ans = cur }
}
returnans%mod}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintmaximumXorProduct(int a, int b, int n) {
int mod = 1000000007;
int lim = (1 << n) - 1;
long ans = 0;
for (int x = 0; x <= lim; x++) {
long cur = (long)(a ^ x) * (b ^ x);
if (cur > ans) ans = cur;
}
return (int)(ans % mod);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmaximumXorProduct(a: Int, b: Int, n: Int): Int {
val mod = 1000000007val lim = (1 shl n) - 1var ans = 0Lfor (x in0..lim) {
val cur = (a xor x).toLong() * (b xor x)
if (cur > ans) ans = cur
}
return (ans % mod).toInt()
}
}
1
2
3
4
5
6
7
8
9
defmaximum_xor_product(a: int, b: int, n: int) -> int:
mod =10**9+7 lim = (1<< n) -1 ans =0for x in range(lim +1):
cur = (a ^ x) * (b ^ x)
if cur > ans:
ans = cur
return ans % mod
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmaximum_xor_product(a: i32, b: i32, n: i32) -> i32 {
let modv =1_000_000_007;
let lim = (1<< n) -1;
letmut ans =0i64;
for x in0..=lim {
let cur = ((a ^ x) asi64) * ((b ^ x) asi64);
if cur > ans { ans = cur; }
}
(ans % modv) asi32 }
}