Adding binary numbers

后端 未结 21 1484
孤独总比滥情好
孤独总比滥情好 2020-11-28 07:50

Does anyone know how to add 2 binary numbers, entered as binary, in Java?

For example, 1010 + 10 = 1100.

21条回答
  •  悲&欢浪女
    2020-11-28 08:10

    here's a python version that

    def binAdd(s1, s2):
        if not s1 or not s2:
            return ''
    
        maxlen = max(len(s1), len(s2))
    
    
        s1 = s1.zfill(maxlen)
        s2 = s2.zfill(maxlen)
    
        result  = ''
        carry   = 0
    
        i = maxlen - 1
        while(i >= 0):
            s = int(s1[i]) + int(s2[i])
            if s == 2: #1+1
                if carry == 0:
                    carry = 1
                    result = "%s%s" % (result, '0')
                else:
                    result = "%s%s" % (result, '1')
            elif s == 1: # 1+0
                if carry == 1:
                    result = "%s%s" % (result, '0')
                else:
                    result = "%s%s" % (result, '1')
            else: # 0+0
                if carry == 1:
                    result = "%s%s" % (result, '1')
                    carry = 0   
                else:
                    result = "%s%s" % (result, '0') 
    
            i = i - 1;
    
        if carry>0:
            result = "%s%s" % (result, '1')
        return result[::-1]
    

提交回复
热议问题