zoukankan      html  css  js  c++  java
  • LeetCode 2

    一、问题描述

    Description:

    You are given two linked lists representing two non-negative numbers. 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.

    Input:

    (2 -> 4 -> 3) + (5 -> 6 -> 4)

    Output:

    7 -> 0 -> 8

    给定两个链表,代表两个非负整数。链表的每个节点包含该整数的一个位上的数字,并且是逆序存储。例如:输入2 -> 4 -> 35 -> 6 -> 4,342 + 465 = 807,故输出7 -> 0 -> 8


    二、解题报告

    思路:由于链表从头到尾依次存放的个位、十位、百位……根据加法的计算方法,每次把对应的位(结点)相加以后,若大于等于10,则进位 …… 依次类推。

    下面上代码:

    /**
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            return add(l1, l2, 0);
        }
    
        ListNode* add(ListNode* l1, ListNode* l2, int carry) {
            if(l1==NULL && l2==NULL && carry==0)  // 递归终止条件
                return NULL;
    
            int sum = carry;  // 对应的两个位相加,并且加上进位
            if(l1!=NULL) sum += l1->val;
            if(l2!=NULL) sum += l2->val;
    
            ListNode* result = new ListNode(0);  // 新建一个结点
            result->val = sum%10;
            result->next = add(l1==NULL?NULL:l1->next, 
                               l2==NULL?NULL:l2->next, 
                               sum>=10?1:0);
    
            return result;
        }
    };





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    《华东交通大学2018年ACM“双基”程序设计竞赛*补》
    《多校补题》
    《HDU多校第五场》
    前端开发框架
    Myeclipse Weblogic Launches下的classpath配置文件目录
    正则表达式:元字符 简
    Freemarker
    SSM整合
    MySQL基础
    Redis与Spring Data Redis
  • 原文地址:https://www.cnblogs.com/songlee/p/5738069.html
Copyright © 2011-2022 走看看