leetcode - 2939. Maximum Xor Product

Description

Given three integers a, b, and n, return the maximum value of (a XOR x) * (b XOR x) where 0 <= x < 2n.

Since the answer may be too large, return it modulo 10^9 + 7.

Note that XOR is the bitwise XOR operation.

Example 1:

复制代码
Input: a = 12, b = 5, n = 4
Output: 98
Explanation: For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98. 
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Example 2:

复制代码
Input: a = 6, b = 7 , n = 5
Output: 930
Explanation: For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Example 3:

复制代码
Input: a = 1, b = 6, n = 3
Output: 12
Explanation: For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Constraints:

复制代码
0 <= a, b < 2^50
0 <= n <= 50

Solution

Solved after help.

Try every bit, if a * b < (a ^ bit) * (b ^ bit), then use bit to change the current bit.

Time complexity: o ( m i n ( log ⁡ a , log ⁡ b , n ) ) o(min(\log a, \log b, n)) o(min(loga,logb,n))

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def maximumXorProduct(self, a: int, b: int, n: int) -> int:
        bit = 1
        while bit < (1 << n):
            if a * b < (a ^ bit) * (b ^ bit):
                a ^= bit
                b ^= bit
            bit <<= 1
        return (a * b) % 1000000007
相关推荐
GreenTea44 分钟前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
风流 少年1 小时前
Spring AI 2.0:Memory
java·后端·spring
码匠许师傅1 小时前
【C++ 面试真题】聊聊 C++ 的移动语义与右值引用
java·c++·面试
小席是个热心肠2 小时前
AI相关的自我学习
java·人工智能·学习
fqq32 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
数智化管理手记4 小时前
海量数据如何沉淀有效数据资产?数据标准化治理方案如何搭建?
java·大数据·人工智能
半夏微凉半夏殇4 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
2501_906565124 小时前
数学之美探究
算法
oier_Asad.Chen4 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环
cfm_29144 小时前
SpringAI + Ollama 本地大模型
java·开发语言·人工智能·语言模型