Leetcode02 两数相加

问题描述:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
实例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
//cpp
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head, *l3 = new ListNode(0);
        head = l3;
        int m = 0, m1, m2;
        while(l1 != NULL || l2 != NULL){
            m1 = l1? l1->val:0;
            m2 = l2? l2->val:0;
            m += m1 + m2;//进位叠加
            l3->next = new ListNode(m%10);
            m /= 10;
            l3 = l3->next;
            l1 = l1? l1->next:l1;//l1为空时保证指针不继续后移
            l2 = l2? l2->next:l2;
        }
        if(m>0) l3->next = new ListNode(m);//进位补充
        l3 = head->next;
        return l3;
    }
};
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#python实现
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l = ListNode(0)
        head = l
        m = 0
        while l1 or l2:
            var1 = var2 = 0
            if l1: var1 = l1.val 
            if l2: var2 = l2.val
            m += var1 + var2
            l.next = ListNode(m%10)
            m = m//10
            l = l.next
            if l1: l1 = l1.next
            if l2: l2 = l2.next
        if(m): l.next = ListNode(m)
        l = head.next
        return l

你可能感兴趣的:(Leetcode,LeetCode数学部分,两数相加)