zoukankan      html  css  js  c++  java
  • Python编程之数据结构与算法练习_003

    题目:给定两个32位整数a和b,返回a和b中较大的。要求:不用任何比较判断。

    不写原理,直接上推导图表:

    代码:

    # 不用任何比较判断找出两个数中较大的数
    import random
    
    def flip(x):
        return x^1
    
    #待测试方法
    def binCompare(x,y):
        z = x - y
        sigX = flip((x>>31)&1)
        sigY = flip((y>>31)&1)
        sigZ = flip(((z>>31)&1))
        sigXYSam = flip(sigX^sigY)
        sigXYDiff = sigX^sigY
        func = sigXYSam*sigZ + sigXYDiff*sigX
        return func*x + flip(func)*y
    
    #常规正确方法
    def normalMethod(x,y):
        return max(x,y)
    
    #对数器
    def Compare(x,y):
        return True if x == y else False
    
    nCount = 0
    maxValue = 1000000 #一百万次
    
    while nCount <= maxValue:
        x = random.randint(-1000000, 1000000) #正负一百万之间的随机数
        y = random.randint(-1000000, 1000000)
        
        binFunResult = binCompare(x,y)
        normalFunResult = normalMethod(x,y) 
        
        if not Compare(binFunResult, normalFunResult):
            print("Fucked.")
            print("Sample:({},{})".format(x,y))
            break
        nCount += 1
    else:
        print("Success.")
  • 相关阅读:
    hdu2328 Corporate Identity
    hdu1238 Substrings
    hdu4300 Clairewd’s message
    hdu3336 Count the string
    hdu2597 Simpsons’ Hidden Talents
    poj3080 Blue Jeans
    poj2752 Seek the Name, Seek the Fame
    poj2406 Power Strings
    hust1010 The Minimum Length
    hdu1358 Period
  • 原文地址:https://www.cnblogs.com/orcsir/p/8745593.html
Copyright © 2011-2022 走看看