LeetCode 2. Add Two Numbers

    xiaoxiao2021-03-25  78

    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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8

    题目很简单,把两个链表按元素加起来,注意进位,另外还要注意两个链表可能元素数量不等。

    还有一个小陷阱就是最后可能会多一个元素。

    解法一:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* root = new ListNode(0), *indexA = l1, *indexB = l2, *indexC = root; int remain = 0; while (indexA != NULL && indexB != NULL) { int total = indexA->val + indexB->val + remain; indexC->val = total % 10; remain = total / 10; indexA = indexA->next; indexB = indexB->next; if (indexA != NULL || indexB != NULL) { indexC->next = new ListNode(0); indexC = indexC->next; } } while (indexA != NULL) { int total = indexA->val + remain; indexC->val = total % 10; remain = total / 10; indexA = indexA->next; if (indexA != NULL) { indexC->next = new ListNode(0); indexC = indexC->next; } } while (indexB != NULL) { int total = indexB->val + remain; indexC->val = total % 10; remain = total / 10; indexB = indexB->next; if (indexB != NULL) { indexC->next = new ListNode(0); indexC = indexC->next; } } if (remain != 0) { indexC->next = new ListNode(remain); } return root; } 解法过长而且用到了额外空间,想想应该可以不需要额外空间的。不过这个解法速度还不错,42ms超过了78.83%的人。

    转载请注明原文地址: https://ju.6miu.com/read-37619.html

    最新回复(0)