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
相关推荐
o丁二黄o5 分钟前
【MyBatisPlus】MyBatisPlus介绍与使用
java
_MyFavorite_8 分钟前
JAVA重点基础、进阶知识及易错点总结(14)字节流 & 字符流
java·开发语言·python
BieberChen28 分钟前
匈牙利匹配算法 (Hungarian Algorithm) 详解
算法
春栀怡铃声36 分钟前
常考排序的梳理
数据结构·算法·排序算法
第二只羽毛36 分钟前
第六章 图
大数据·数据结构·算法·深度优先·图论·广度优先·宽度优先
好家伙VCC39 分钟前
**CQRS模式实战:用Go语言构建高并发读写分离架构**在现代分布式系统中,随着业务复杂度的提升和用户量的增长,传统的单数据库模型逐
java·数据库·python·架构·golang
fy1216339 分钟前
Java进阶——IO 流
java·开发语言·python
二妹的三爷40 分钟前
Node.JS 版本管理工具 Fnm 安装及配置(Windows)
java
cngkqy41 分钟前
NoClassDefFoundError: org/apache/poi/logging/PoiLogManager
java
l1o3v1e4ding1 小时前
Java网站项目集成GO-FLY开源在线客服系统功能,集成IM即时通信
java·golang·开源