Binary numbers in Python

前端 未结 9 2112
孤独总比滥情好
孤独总比滥情好 2020-12-04 11:14

How can I add, subtract, and compare binary numbers in Python without converting to decimal?

9条回答
  •  自闭症患者
    2020-12-04 11:52

    '''
    I expect the intent behind this assignment was to work in binary string format.
    This is absolutely doable.
    '''
    
    def compare(bin1, bin2):
        return bin1.lstrip('0') == bin2.lstrip('0')
    
    def add(bin1, bin2):
        result = ''
        blen = max((len(bin1), len(bin2))) + 1
        bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
        carry_s = '0'
        for b1, b2 in list(zip(bin1, bin2))[::-1]:
            count = (carry_s, b1, b2).count('1')
            carry_s = '1' if count >= 2 else '0'
            result += '1' if count % 2 else '0'
        return result[::-1]
    
    if __name__ == '__main__':
        print(add('101', '100'))
    

    I leave the subtraction func as an exercise for the reader.

提交回复
热议问题