Ruby version


  • 0
    D
    # @param {ListNode} l1
    # @param {ListNode} l2
    # @return {ListNode}
    def add_two_numbers(l1, l2)
        ret, cur = nil
        sum = 0
        
        loop {
            if not l1 and not l2
                cur.next = ListNode.new(sum) if cur and sum > 0
                break
            end
            
            if l1 and l2
                sum += l1.val + l2.val
                l1 = l1.next
                l2 = l2.next
            elsif l1
                sum += l1.val
                l1 = l1.next
            else
                sum += l2.val
                l2 = l2.next
            end
            
            if not cur
                ret = cur = ListNode.new(sum % 10)
            else
                cur = cur.next = ListNode.new(sum % 10)
            end
            
            sum /= 10
        }
    
        ret
    end
    

Log in to reply
 

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