2. Add Two Numbers[M]两数相加

题目


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.

思路


主要是考察链表的求和,由于链表中存放的是逆序的数字,所以两个数的个位数已经对齐,不用考虑对齐问题。其次要考虑到进位的问题:

  • 当前位数字:sum %10
  • 进位:sum / 10

C++

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
    ListNode* result = new ListNode(-1);
    ListNode* aux = result; //辅助,用来处理中间链表
    int carry = 0;
    while(l1 != nullptr || l2 != nullptr || carry != 0){ 
        
        //这种方法使得当其中一个链表为空时,也能作加法,从而能够同时对两个链表进行循环
        int a = l1 ? l1->val : 0; //判断链表当前是否为空,如果为空,则值为0
        int b = l2 ? l2->val : 0;

        int sum = a + b + carry;
        carry = sum / 10; //进位用取模来获得
        aux->next = new ListNode(sum%10); //通过取模消除进位的影响
        aux = aux ->next;
        if(l1 != nullptr )
            l1 = l1->next;
        if(l2 != nullptr )
            l2 = l2->next;
    }
             
    return result->next;
}

Python

def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(-1)
        aux = result
        carry = 0  
        while(l1 or l2 or carry):
            a = l1 and l1.val or 0
            b = l2 and l2.val or 0
            sum = a + b + carry
            carry = sum / 10
            aux.next = ListNode (sum % 10)
            aux = aux.next
            if(l1):
                l1 = l1.next
            if(l2):
                l2 = l2.next
                
        return result.next
posted @ 2019-05-29 15:11  风雪初晴,宜下江南  阅读(146)  评论(0编辑  收藏  举报