8ms golang version


  • 0
    P

    a 8ms golang version, it's not short and elegant, but easy to understand

    func addBinary(a string, b string) string {
    	result := ""
    	i, j := len(a), len(b)
    	carry := false
    	for i > 0 || j > 0 {
    		sum, numA, numB := 0, 0, 0
    		if i > 0 {
    			numA, _ = strconv.Atoi(string(a[i-1]))
    			sum += numA
    			i--
    		}
    		if j > 0 {
    			numB, _ = strconv.Atoi(string(b[j-1]))
    			sum += numB
    			j--
    		}
    		if carry {
    			sum += 1
    		}
    		if sum >= 2 {
    			carry = true
    			sum -= 2
    		} else {
    			carry = false
    		}
    		result = strconv.FormatInt(int64(sum), 10) + result
    	}
    	if carry {
    		result = "1" + result
    	}
    	return result
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.