NOTE

Big Number Addition

Add large numbers represented as strings by scanning from right to left and carrying.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Read two numbers as strings, write a function to calculate their sum, and return the result as a string. (The string length does not exceed 100000, and each string contains only the ten characters ‘0’~‘9’.)

2. Approach

  1. Approach 1
    • Similar to Add Two Numbers: scan from right to left, take the remainder modulo 10 after addition, and record the carry

3. Implementation

  • go
func addStrings(num1 string, num2 string) string {
    i := len(num1)-1
    j := len(num2)-1
    jinwei := 0
    var res string
    for i >= 0 || j >= 0 || jinwei > 0 {
        sum := 0
        if i >= 0 {
            sum += int(num1[i])-'0'
            i--
        }
        if j >= 0 {
            sum += int(num2[j])-'0'
            j--
        }
        sum += jinwei
        yushu := sum % 10
        jinwei = sum / 10
        res = fmt.Sprintf("%v%v", yushu, res)
    }
    return res
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub