Binary numbers in Python

前端 未结 9 2136
孤独总比滥情好
孤独总比滥情好 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:34

    Not sure if helpful, but I leave my solution here:

    class Solution:
        # @param A : string
        # @param B : string
        # @return a strings
        def addBinary(self, A, B):
            num1 = bin(int(A, 2))
            num2 = bin(int(B, 2))
            bin_str = bin(int(num1, 2)+int(num2, 2))
            b_index = bin_str.index('b')
            return bin_str[b_index+1:]
    
    s = Solution()
    print(s.addBinary("11", "100"))
    

提交回复
热议问题