题目描述

给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数...),求这个两个数的和,结果也用链表表示。
输入:(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. java安全编码指南之:lock和同步的正确使用

    目录 简介 使用private final object来作为lock对象 不要synchronize可被重用的对象 不要sync Object.getClass() 不要sync高级并发对象 不要使 ...

  2. MySQL 日志详解

    一.MySQL 日志分类 MySQL 日志主要包含:错误日志.查询日志.慢查询日志.事务日志.二进制日志. 错误日志: -log-err (记录启动.运行.停止 MySQL 服务时出现的信息) 查询日 ...

  3. OAth 2.0 的白话讲解

    一.OAuth2.0是什么,主要做什么用的? 官方注解 简单说,OAuth 就是一种授权机制.数据的所有者告诉系统,同意授权第三方应用进入系统,获取这些数据.系统从而产生一个短期的进入令牌(token ...

  4. (SpringBoot-Jpa)使用Idea数据库自动脚本Generate POJOS生成 Entity对象,

    因:使用SpringBoot -jpa,需要手动配置Entity 但是如果你的表中有很多属性,或者有很多表怎么办?? 每个手动写? 还是用mybatis.写mapper??? 解决:使用idea自动工 ...

  5. java流程控制学习

    Java流程控制 计算的步骤就是算法. 1.用户交互Scanner next()不能得到带有空格的字符串.[它是以空格为结束符]nextline()可以,[它是以回车为结束符] 2.顺序结构 从上到下 ...

  6. 多测师讲解接口测试 _理论基础知识001_高级讲师肖sir

    前言: 我们今天进入接口测试的学习! 今天学习的内容是偏向理论 接口理论 了解接口测试(1) 一.什么是接口测试? 接口统称api,即程序与程序之间的对接.交接.交互.是测试系统组件间接口的一种测试. ...

  7. MeteoInfoLab脚本示例:subplot

    subplot命令可以自动等间距分配多个坐标系(Axes),命令中有三个参数,前两个定义了行数和列数,第三个指定了当前的坐标系(Axes),绘图命令是作用在当前坐标系中的. 脚本程序: def f(t ...

  8. 本地ssh快速登录 ssh免密登录

    每次登录都要ssh -p wang@xx.xx.xx.xx 虽然做了公钥验证 https://www.cnblogs.com/php-linux/p/10795913.html 不需要输入密码,但是每 ...

  9. ASP.NET实现进度条效果【转】

     原文地址:http://www.jb51.net/article/115310.htm 这篇文章主要为大家详细介绍了ASP.NET实现简单的进度条效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一 ...

  10. Linux 生产主流版本

    CentOS 8 下载 https://mirrors.aliyun.com/centos/8.1.1911/isos/x86_64/CentOS-8.1.1911-x86_64-dvd1.iso L ...