Add Two Numbers 解法

来源:互联网 发布:radiohead知乎 编辑:程序博客网 时间:2024/06/09 20:13

Add Two Numbers 解法


第一周题目
难度:Media
LeetCode题号:2

题目

Description:

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.

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


思考

先将两个链表尾部填充0使得两个链表的长度一样长
然后对每一位模拟加法,addNum为当前同一位两个数的和,remainder是和的个位数,是结果中此位的数字,carry是和的十位数,是进位,用于下一位的加法。
循环到最后时,carry有两种情况,0或1,当carry为1时不处理,当carry为0时,把前一位的next设为null


代码

class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        // 扩充链表,填0,使得两个链表一样长        ListNode* l1_expand = l1;        ListNode* l2_expand = l2;        while (l1_expand->next != NULL && l2_expand->next != NULL) {            l2_expand = l2_expand->next;            l1_expand = l1_expand->next;        }        if (l1_expand->next == NULL) {            while (l2_expand->next != NULL) {                l2_expand = l2_expand->next;                ListNode* temp = new ListNode(0);                l1_expand->next = temp;                l1_expand = l1_expand->next;            }        } else {            while (l1_expand->next != NULL) {                l1_expand = l1_expand->next;                ListNode* temp = new ListNode(0);                l2_expand->next = temp;                l2_expand = l2_expand->next;            }        }        ListNode * rel_index = new ListNode(0);        ListNode * result = rel_index;        ListNode * old_rel_index;        int carry = 0, remainder = 0;        while (l1 != NULL && l2 != NULL) {            int addNum = carry + l1->val + l2->val;            remainder = addNum % 10;            carry = addNum / 10;            rel_index->val = remainder;            old_rel_index = rel_index;            rel_index->next = new ListNode(0);            rel_index = rel_index->next;            l1 = l1->next;            l2 = l2->next;        }        rel_index->val = carry;        if (carry == 0) {            old_rel_index->next = NULL;        }        return result;    }};
原创粉丝点击