用链表实现大整数加法

背景:LeetCode – 2. Add Two Numbers

描述:

给你两个不为空的链表,而且链表中的数字是反序的,现在要你求出这两个链表所代表的数字的和,同样用链表表示。

链表的定义:

 // Definition for singly-linked list.
 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

代码:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *ret = l1, *pre = l1;
        int up = 0;
        while (l1 != NULL && l2 != NULL) {
            l1->val = l1->val + l2->val + up;
            up = l1->val / 10;
            l1->val %= 10;
            pre = l1;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l1 == NULL)
            pre->next = l2;
        l1 = pre->next;
        while (l1 != NULL) {
            l1->val = l1->val + up;
            up = l1->val / 10;
            l1->val %= 10;
            pre = l1;
            l1 = l1->next;
        }
        if (up != 0) {
            ListNode *tmp = new ListNode(up);
            pre->next = tmp;
        }
        return ret;
    }
};
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/FlushHip/article/details/70740039
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞