【leetcode】2 Add Two Numbers

题目说明

https://leetcode-cn.com/problems/add-two-numbers/description/
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

解法1

两个链表长度相同的部分,对位相加,注意需要还需要加上上一次相加的进位值。得到结果后,将个位数存入结果链表中,十位数等待下一次相加使用。
然后对较长的链表进行相同操作,只不过只跟进位值相加。
容易忽略的是最后可能十位数还有值,需要单独进行处理

/*
 * 时间复杂度:O(n)
 * 添加新链表存储和的结果
 * 每次相加,需要将两个链表对位数值与前一次的十位数 相加
 * 将和的个位数添加至新链表中
 * 和的十位数等待下一次相加
 * 两个链表长度可能不一致,所以对位相加完成后,还需要对长度更长的链表进行操作。
 * 最后可能十位数还有值,所以还要对十位数单独作判断,如果有值则添加到新链表
 */
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *cur1 = l1;
    ListNode *cur2 = l2;
    ListNode *l3 = new ListNode(0);
    ListNode *cur3 = l3;
    int tens  = 0;//和的十位数
    int units = 0;//和的个位数
    int sum = 0;//和的数值

    while(cur1 && cur2){
        sum = cur1->val + cur2->val + tens;
        units = sum % 10;
        tens = sum / 10;
        ListNode *temp = new ListNode(units);
        cur3->next = temp;
        cur3 = cur3->next;
        cur1 = cur1->next;
        cur2 = cur2->next;
    }

    ListNode *last = (cur1 == NULL)?cur2:cur1;//取非空
    while(last){
        sum = last->val + tens;
        units = sum % 10;
        tens = sum / 10;
        ListNode *temp = new ListNode(units);
        cur3->next = temp;
        cur3 = cur3->next;
        last = last->next;
    }

    if (tens){
        ListNode *temp = new ListNode(tens);
        cur3->next = temp;
        cur3 = cur3->next;
    }

    return l3->next;
}

猜你喜欢

转载自www.cnblogs.com/JesseTsou/p/9570199.html