002-Add Two Numbers 两个数字相加

Description:You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.

给两个非空链表,表示两个非负的整数,数字是以相反的顺序存储,每个节点包含一个数字。 求两个数字的和,并以链表的形式返回。

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

type ListNode struct {
    Val  int
    Next *ListNode
}

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
}

两个数字字符串相加

//转为链表相加
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
}

两个数字字符串相加2

//字符串 数字相加
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)
}