Add Two Numbers--LeetCode

来源:互联网 发布:济南大学网络教学平台 编辑:程序博客网 时间:2024/06/05 19:54

1.题目

Add Two Numbers

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

2.题意

给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点都包含一个数字,将两个数相加,以链表形式返回。
假定两个数字不包含任何前导零,除了数字0本身。

3.分析

思路很明确,按照位数相加,维护当前位和进位即可
int n1 = l1 != nullptr ? l1->val : 0;
int n2 = l2 != nullptr ? l2->val : 0;
int sum = n1 + n2 + carry;
注意判断l1与l2是否为空,计算sum的值记得加上carry,否则会出错

4.代码

class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        ListNode *dummy = new ListNode(-1);        ListNode *cur = dummy;        int carry = 0;        while(l1 != nullptr || l2 != nullptr)        {            int n1 = l1 != nullptr ? l1->val : 0;            int n2 = l2 != nullptr ? l2->val : 0;            int sum = n1 + n2 + carry;            carry = sum / 10;            cur->next = new ListNode(sum % 10);            cur = cur->next;            if(l1 != nullptr)                l1 = l1->next;            if(l2 != nullptr)                l2 = l2->next;        }        if(carry)            cur->next = new ListNode(1);        return dummy->next;    }};
原创粉丝点击