Add Strings 字符串相加

Description

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

Note
  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
注意
  1. num1 和num2 的长度都小于 5100.
  2. num1 和num2 都只包含数字 0-9.
  3. num1 和num2 都不包含任何前导零。
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
Example
Input: num1 = "123", num2 = "456"
Output: 579
Explanation: "123 + "456" = "579".
Solution
//直接处理字符串相加
func addTwoString1(num1 string,num2 string)string  {
    carry := 0
    maxLen := maxInt(len(num2),len(num1))
    result := make([]byte,maxLen+1)
    for i := 0 ; i < maxLen; i ++ {
        sum := carry
        if len(num1) > i {
            v1 ,_ := strconv.Atoi(string(num1[len(num1) -i -1]))
            sum += v1
        }
        if len(num2) > i {
            v2 ,_ := strconv.Atoi(string(num2[len(num2) -i -1]))
            sum += v2
        }
        carry = sum/10
        result[maxLen - i] = []byte(strconv.Itoa(sum%10))[0]
    }
    if carry > 0 {
        result[0] = []byte(strconv.Itoa(carry))[0]
    }else {
        return string(result[1:])
    }
    return  string(result)
}
Solution 02
type ListNode struct {
    Val  int
    Next *ListNode
}


//两字符串相加
func addTwoString(num1 string,num2 string)string  {
    l1 := makeListNode(num1)
    l2 := makeListNode(num2)
    l3 := addTwoNumbers(l1,l2)
    return  listNodeToString(l3)
}

//字符串转换为数字链表
func makeListNode(s string)*ListNode  {
    node := new(ListNode)
    current := node
    for i := len(s) - 1; i >=0; i -- {
        current.Next = new(ListNode)
        current.Val ,_ = strconv.Atoi(string(s[i]))
        current = current.Next
    }
    return node
}

//数字链表转为字符串
func listNodeToString(l *ListNode)string  {
    result := ""
    for l != nil {
        if l.Next != nil || l.Val != 0 {
            result  = fmt.Sprintf("%d%s",l.Val,result)
        }
        l = l.Next
    }
    return result
}

 //计算结果   
func addTwoNumbers(l1 *ListNode,l2 *ListNode) *ListNode  {
    head := &ListNode{0,nil}
    current := head
    carry := 0
    for l1 != nil || l2 != nil || carry > 0 {
        sum := carry
        if l1 != nil {
            sum += l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            sum += l2.Val
            l2 = l2.Next
        }
        carry = sum /10
        current.Next = new(ListNode)
        current.Next.Val = sum%10
        current = current.Next
    }
    return head.Next
}