Wednesday, April 01, 2015

subtract two string ints

100 - 99 = 1
99 - 100 = -1
9 - 1 = 8
1 - 9 = -8
9 - 9 = 0
90 - 90 = 0

subtract(s1, s2):
    // flip if s2 > s1
    if is-greater(s2, s1):
        buffer = subtract(s2, s1)
        buffer.insert(0, "-")
        return buffer
    // s1 - s2
    i = s1.length-1, j = s2.length-1
    carry = 0
    buffer = new
    while i >= 0: // i >= j always
        a, b = 0
        if i >= 0:
            a = s1[i] - '0'
            i--
        if j >= 0:
            b = s2[j] - '0'
            j--
        sum = a-b -carry
        if sum < 0:
            sum += 10
            carry = 1
        else:
            carry = 0
        buffer.append(sum)
    // remove leading 0s except last
    i = buffer.length-1
    while i > 0 && buffer[i] == '0':
        buffer.length--
        i--
    // carry will always be 0 as s1 >= s2
    return buffer.reverse()

// clean numbers only (+ve, no spaces, no padded, etc.)
is-greater(a, b):
    result = a.length() > b.length()
    if a.length() == b.length():
        for i = 0, i < a.length(), i++:
            if a[i] > b[i]:
                result = true
                break
    return result

compare(sa, sb):
    c = sa.length().compare(sb.length())
    if c != 0:
        return c
    for i = 0, i < sa.length(), i++:
        c = sa[i].compare(sb[i])
        if c != 0:
            return c
    return 0

No comments:

Post a Comment