# 不使用比较和条件判断实现min函数的一种方法

### Solution

``````a=011010
b=010110
``````

``````"""
myMin(0b011010, 010110)

(1)
011010  A
010110  B
^ same 0 vs. 0

(2)
011010  A
010110  B
^ same 1 vs. 1

(3)
011010  A
010110  B
^ diff, sign_A=1, sign_B=0

(4)
011110  A'
010110  B'
^ A_i |= sign_A, B_i |= sign B

(5)(6)
011111  A''
010110  B''
^ A_i |= sign_A, B_i |= sign B

A'' & B'' = B
"""

def myMin(a, b):
found = 0
sign_a, sign_b = 0, 0
for i in range(32, -1, -1):
bit = 1 << i
xa, xb = (a & bit) >> i, (b & bit) >> i

#   d = xa ^ xb
# else:
#   d = 0

# if xa ^ xb == 1:
#   found = 1
found |= xa ^ xb

# if d:
#   sign_a, sign_b = xa, xb
sign_a |= d & xa
sign_b |= d & xb

a |= sign_a * bit
b |= sign_b * bit
return a&b

# 用于生成随机测试用例测试正确性
import random, time
loop = 0
MAX = 1<<32
while True:
a, b = random.randint(0, MAX), random.randint(0, MAX)
if myMin(a, b) != min(a, b):
print(f"min({a}, {b}) = {min(a, b)} != {myMin(a, b)}")
break
loop += 1
print(loop, end='\r')
time.sleep(0.001)
``````

``````mask = (1 << 32) - 1; // 0b111111...111
ans = (flag * mask) & a + (!flag * mask) & b;
``````

原文作者：Glowming
原文地址: https://www.cnblogs.com/glowming/p/min-without-condition-and-comparison.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。