小编Ram*_*Ram的帖子

给定 N,返回满足等式的 M:N + M = 2 * (N XOR M)

问题

Given N, return M that satisfy the equation: N + M = 2 * (N ^ M)
Run Code Online (Sandbox Code Playgroud)

约束

1 <= Test Cases = 10^5; 
1 <= N <= 10^18
Run Code Online (Sandbox Code Playgroud)

我在其中一项招聘挑战中遇到了这个问题。

通过反复试验的方法,我发现了一种模式 -这样的 M 存在于 N/3 和 3N 之间,并且N + M 是偶数。所以我对它进行了编码,提交后,我的解决方案只能通过一半的测试用例。这不是什么优化,因为这种方法的时间复杂度与蛮力解决方案的时间复杂度相同。

我知道我的解决方案不是最佳解决方案。

这是我的解决方案:

def solve(n):
    m = n//3
    end = 3*n
    
    # If both m and n are odd/even, their sum will be even
    if (m&1 == 1 and n & 1 == 1) or …
Run Code Online (Sandbox Code Playgroud)

python algorithm bit-manipulation xor bitwise-operators

1
推荐指数
1
解决办法
98
查看次数