Friday, July 25, 2014

add two string ints

"123", "4" => "127"
"99", "999" => "1098"
"9", "9" => "18"
string add(string s1, string s2):
    i = s1.length-1, j = s2.length-1
    carry = 0
    buffer = new
    while i >= 0 || j >= 0 || carry > 0:
        a = 0
        if i >= 0:
            a = s1[i] -'0'
            i--
        b = 0
        if j >= 0:
            b = s2[j] -'0'
            j--
        digit = a+b +carry
        carry = 0
        if digit >= 10:
            carry = digit /10
            digit = digit %10
        buffer.append(digit)
    return buffer.reverse()
[Hat tip to SM]

No comments:

Post a Comment