题目描述

给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数...),求这个两个数的和,结果也用链表表示。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8

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

示例1

输入

复制

{0},{0}

输出

复制

{0}
示例2

输入

复制

{0},{1}

输出

复制

{1}

/**
     *
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // write code here
        //创建结果链表的头结点,默认该节点中的value为-1
        ListNode dummy=new ListNode(-1);
        ListNode pre=dummy;
        //进位标识carry,默认为0
        int carry =0;
        //遍历链表,当两个链表都为空时,退出
        while (l1!=null || l2 !=null){
            //判断该节点是否为空,当节点为空时,用0补全,不为空时,加数即为节点的值
            int d1=(l1==null) ?0:l1.val;
            int d2=(l2==null)? 0:l2.val;
            //对节点求和,注意:求和是需要考虑到进位
            int sum=d1+d2+carry;
            //更新进位标识,
            carry=(sum>=10)?1:0;
            //sum%10标识求和的个位数,将其保存到结果链表中
            pre.next=new ListNode(sum%10);
            pre=pre.next;
            if (l1!=null) l1=l1.next;
            if (l2!=null) l2=l2.next;
            
        }
        //重点  这是一个特殊情况,当两个链表计算完后
        //还需要判断进位标识是否为1,如果为1,如28+81=104,需要创建一个节点保存最高位
        if (carry ==1)
            pre.next=new ListNode(1);
        return dummy.next;
    }

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     *
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // write code here
        ListNode fake(0);
        ListNode *p=&fake;
        int carry=0;
        while (l1 || l2 || carry)
        {
            int sum=(l1?l1->val:0)+(l2?l2->val:0)+carry;
            carry=sum/10;
            p->next=new ListNode(sum%10);
            p=p->next;
            l1=l1?l1->next:nullptr;
            l2=l2?l2->next:nullptr;
            
        }
        return fake.next;
    }
};

leetcode144add-two-numbers的更多相关文章

  1. Java 位运算2-LeetCode 201 Bitwise AND of Numbers Range

    在Java位运算总结-leetcode题目博文中总结了Java提供的按位运算操作符,今天又碰到LeetCode中一道按位操作的题目 Given a range [m, n] where 0 <= ...

  2. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  3. [LeetCode] Add Two Numbers II 两个数字相加之二

    You are given two linked lists representing two non-negative numbers. The most significant digit com ...

  4. [LeetCode] Maximum XOR of Two Numbers in an Array 数组中异或值最大的两个数字

    Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. Find the maximum re ...

  5. [LeetCode] Count Numbers with Unique Digits 计算各位不相同的数字个数

    Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. Examp ...

  6. [LeetCode] Bitwise AND of Numbers Range 数字范围位相与

    Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers ...

  7. [LeetCode] Valid Phone Numbers 验证电话号码

    Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bas ...

  8. [LeetCode] Consecutive Numbers 连续的数字

    Write a SQL query to find all numbers that appear at least three times consecutively. +----+-----+ | ...

  9. [LeetCode] Compare Version Numbers 版本比较

    Compare two version numbers version1 and version1.If version1 > version2 return 1, if version1 &l ...

  10. [LeetCode] Sum Root to Leaf Numbers 求根到叶节点数字之和

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...

随机推荐

  1. 【题解】[ZJOI2009]狼和羊的故事

    题目戳我 \(\text{Solution:}\) 显然思路,把所有羊看成一个源点,所有狼看成一个汇点,格子之间连容量为\(1\)的边,直接跑最小割. 技巧: 注意到篱笆不能把羊给割掉,狼同理.所以, ...

  2. mysql5.7.23 解压版 密码忘记了咋办??

    mysql 5.7.23  err文件: 查看log中保存的 密码 记下密码,重新启动MySQL服务,并进入CMD命令行,在此使用mysql -u root -p登陆,键入密码 进入数据库后,使用se ...

  3. shell脚本算术运算

    自增自减操作 用let命令可以实现自增自减的命令,不需要$符号: #!/bin/bash set -e n=100 let n++ echo $n 还可以实现自增自减指定的值: #!/bin/bash ...

  4. 【线段树分治】Dash Speed

    代码的美妙 #include <bits/stdc++.h> %:pragma GCC optimize(3) using namespace std; const int maxn=7e ...

  5. 转 Swoole】用swoole简单实现MySQL连接池

    MySQL连接池 在传统的网站开发中,比如LNMP模式,由Nginx的master进程接收请求然后分给多个worker进程,每个worker进程再链接php-fpm的master进程,php-fpm再 ...

  6. PHP7下的协程实现 转

        前言 相信大家都听说过『协程』这个概念吧. 但是有些同学对这个概念似懂非懂,不知道怎么实现,怎么用,用在哪,甚至有些人认为yield就是协程! 我始终相信,如果你无法准确地表达出一个知识点的话 ...

  7. Django创建表时报错django.db.utils.InternalError: (1366问题解决记录

    问题出现 执行Python manage.py makemigrations生成创建表的py文件 执行python manage.py migrate创建数据表 界面出现报错 问题原因 网上搜索原因, ...

  8. js鼠标、键盘事件实例代码

    1. 鼠标的哪个按键被点击? <html> <head> <script type="text/javascript"> function wh ...

  9. matplotlib作图 归零编码、曼切斯特编码、非归零编码、差分曼切斯特编码

    效果图 代码 import matplotlib.pyplot as plt config = { 'color': 'black', 'lw': 5, } def init(): plt.figur ...

  10. 微信小程序-基于高德地图API实现天气组件(动态效果)

    微信小程序-基于高德地图API实现天气组件(动态效果) ​ 在社区翻腾了许久,没有找到合适的天气插件.迫不得已,只好借鉴互联网上的web项目,手动迁移到小程序中使用.现在分享到互联网社区中,帮助后续有 ...