《算法分析与设计》Week 14

2. Add Two Numbers



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.

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


Solution:

一、题意理解

     就是实现两个大数相加,加速和被加数均以链表的方式给了出来。


二、分析

     1、题目看似简单,但实现起来还是有一些细节要处理的,不仅要记住carry位,而且因为不能越界,所以要判断哪一个加数位数较多,以便对之后的位做处理。另外输出结果也要是一个链表,并不是传统的字符串类型的大数相加,所以在处理链表的时候也要注意细节。

     2、所以流程即为,从左到右依次相加,有进位则记住进位,将个位数储存到新的节点中。到了较短的数的结尾,要将较长的数的后面的数依次链接到结果的后面,也要注意最后一个进位。

     3、代码如下,有注释。

/**
 * 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* head = new ListNode(0);
        ListNode* cur = head;
        int sum;
        int carry = 0;
        while(l1 && l2)
        {
            sum = l1->val + l2->val + carry;
            carry = sum >= 10? 1:0;
            
            ListNode* newNode = new ListNode(sum%10);
            cur->next = newNode;
            cur = newNode;
            l1 = l1->next;
            l2 = l2->next;
        }
        ListNode* longl = NULL;
        if(l1)
            longl = l1;
        else if(l2)
            longl = l2;
        
        // 对较长的链表继续进行运算
        while(longl != NULL)
        {
            sum = longl->val + carry;
            carry = sum >= 10? 1:0;
            
            ListNode* newNode = new ListNode(sum%10);
            cur->next = newNode;
            longl = longl->next;
            cur = newNode;
        }
        // 处理最后的进位
        if(carry != 0)
        {
            ListNode* newNode = new ListNode(carry);
            cur->next = newNode;
        }

        ListNode *result = head->next;
        delete head;
        return result;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值