[LintCode] Add Two Numbers 两个数字相加

简介:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

LeetCode上的原题,请参见我之前的博客Add Two Numbers

class Solution {
public:
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    ListNode *addLists(ListNode *l1, ListNode *l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        int carry = 0;
        while (l1 || l2) {
            int num1 = l1 ? l1->val : 0;
            int num2 = l2 ? l2->val : 0;
            int sum = num1 + num2 + carry;
            cur->next = new ListNode(sum % 10);
            carry = sum / 10;
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
            cur = cur->next;
        }
        if (carry) cur->next = new ListNode(1);
        return dummy->next;
    }
};

本文转自博客园Grandyang的博客,原文链接:两个数字相加[LintCode] Add Two Numbers ,如需转载请自行联系原博主。

相关文章
|
8月前
|
存储 缓存 算法
【手绘算法】力扣 2 两数相加(Add Two Numbers)
Hi,大家好,我是Tom。一个美术生转到Java开发的程序员。今天给大家分享的是力扣题第2题,求两数相加。在解题过程中,也会手写一些伪代码。当然,如果想要完整的源码的话,可以到我的个人主页简介中获取。 这道题属于中等难度,通过率只有42%。
56 0
|
11月前
力扣--字符串相加
力扣--字符串相加
每日一题---12. 整数转罗马数字[力扣][Go]
每日一题---12. 整数转罗马数字[力扣][Go]
每日一题---12. 整数转罗马数字[力扣][Go]
每日一题---13. 罗马数字转整数[力扣][Go]
每日一题---13. 罗马数字转整数[力扣][Go]
每日一题---13. 罗马数字转整数[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
每日一题 --- 713. 乘积小于 K 的子数组[力扣][Go]
HDOJ(HDU) 2113 Secret Number(遍历数字位数的每个数字)
HDOJ(HDU) 2113 Secret Number(遍历数字位数的每个数字)
92 0
|
存储 Java Python
LeetCode 2:两数相加 Add Two Numbers
​给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
668 0