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
相关推荐
_Jimmy_15 分钟前
Nacos的三层缓存是什么
java·缓存
朝新_41 分钟前
【实战】动态 SQL + 统一 Result + 登录校验:图书管理系统(下)
xml·java·数据库·sql·mybatis
谈笑也风生43 分钟前
经典算法题之子集(四)
算法
mit6.8241 小时前
划分dp+滑窗+前缀和|deque优化
算法
百***92021 小时前
java进阶1——JVM
java·开发语言·jvm
迦蓝叶1 小时前
RDF 与 RDFS:知识图谱推理的基石
java·人工智能·数据挖掘·知识图谱·语义网·rdf·rdfs
百锦再1 小时前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
yaoxin5211231 小时前
238. Java 集合 - 使用 ListIterator 遍历 List 元素
java·python·list
爱分享的Shawn_Salt1 小时前
IntelliJ IDEA初始化指南
java·ide·intellij-idea
Dxxyyyy1 小时前
零基础学JAVA--Day32(ArrayList底层+Vector+LinkedList)
java·开发语言