• [LeetCode] 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 contains a single digit. Add the two numbers and return the sum as a linked list.
    给定两个非空链表表示两个整数。整数的每一位倒序存储,链表内的每一个节点仅包含一个数字,将这两个数相加,以单链表的形式返回答案。

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.
    你可以假定除了 0 本身外,两数都不含前导 0。

    Examples

    Example 1

    Input: l1 = [2,4,3], l2 = [5,6,4]
    Output: [7,0,8]
    Explanation: 342 + 465 = 807.
    

    Example 2

    Input: l1 = [0], l2 = [0]
    Output: [0]
    

    Example 3

    Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
    Output: [8,9,9,9,0,0,0,1]
    

    Constraints

    • The number of nodes in each linked list is in the range [1, 100].
    • 0 <= Node.val <= 9
    • It is guaranteed that the list represents a number that does not have leading zeros.

    Solution

    做这题的时候需要注意两点:

    • 两数长度不一样时的处理;

    • 相加到最后的进位处理。

    得益于 Kotlin 对可空元素的语法糖,我不需要单独考虑第一种情况,代码如下:

    /**
     * Example:
     * var li = ListNode(5)
     * var v = li.`val`
     * Definition for singly-linked list.
     * class ListNode(var `val`: Int) {
     *     var next: ListNode? = null
     * }
     */
    class Solution {
        fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
            var p = l1
            var q = l2
            val dummy = ListNode(-1)
            var r: ListNode? = dummy
            var carry = 0
    
            while (p != null || q != null) {
                val digit = (p?.`val`?:0) + (q?.`val`?:0) + carry
                carry = digit / 10
                r?.next = ListNode(digit % 10)
                r = r?.next
                p = p?.next
                q = q?.next
            }
            
            if (carry != 0) {
                r?.next = ListNode(carry)
            }
    
            return dummy.next
        }
    }
    
  • 相关阅读:
    Safe Path(bfs+一维数组存图)
    一维树状数组入门
    Ancient Go(简单DFS)
    Sudoku(简单DFS)
    Strategic game(树形DP入门)
    多线程源码分析
    Navicat premium12的破解方法,无需注册码
    MySQL和Oracle的区别
    java Web项目中什么场景中会用到java多线程?
    TCP协议三次握手、四次断开 过程分析
  • 原文地址:https://www.cnblogs.com/zhongju/p/14118651.html
Copyright © 2020-2023  润新知