Golang concise 26ms solution


  • 0

    If you come up with more optimized way, please let me know.

    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
        cur := &ListNode{}
        head := cur
        
        sum, co := 0, 0
        for co != 0 || l1 != nil || l2 != nil {
            cur.Next = &ListNode{}
            cur = cur.Next
            
            sum = co
            if l1 != nil {
                sum += l1.Val
                l1 = l1.Next
            }
            if l2 != nil {
                sum += l2.Val
                l2 = l2.Next
            }
            
            co = sum / 10
            cur.Val = sum % 10
        }
        return head.Next
    }
    

    We can add this part just below the start of for ,

            if l1 == nil && co == 0 {
                    cur.Next = l2
                    break
            }
            if l2 == nil && co == 0 {
                    cur.Next = l1
                    break
            }
    

    but it didn't improve the time of submission.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.