Leetcode 刷题笔记二 两数相加(使用链表) -- scala版本

Leetcode 刷题笔记二 两数相加(使用链表) -- scala版本

原地址:两数相加

问题描述:

题干:

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
Explanation: 342 + 465 = 807.

简要思路分析:

使用链表的思路,同步推进链表上的数字进行计算。推进过程中进行链表非空的判断,若一条链上的数字已经跑完,将其值域设为0,在计算过程中,计算l1的值域和l2的值域的和, 判断其值是否会有进位,将进位与剩余数字作为一个元组保存,用于下一步的迭代。

代码补充:

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
object Solution {
    def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
        //
        def calculate(l1: ListNode, l2: ListNode, carryOver: Option[Int]): ListNode={
        //
        if (l1 == null && l2 == null && carryOver.isEmpty){
            null
        }
        else{
            val x1 = if(l1 == null) 0 else l1.x
            val x2 = if(l2 == null) 0 else l2.x
            
            val (n, co) = {
                val sum = x1 + x2 + carryOver.getOrElse(0)
                if (sum > 9){
                    (sum%10, Some(sum/10))
                }
                else{
                    (sum, None)
                }
            }
            
            val r1 = new ListNode(n)
            val n1 = if(l1 == null) null else l1.next
            val n2 = if(l2 == null) null else l2.next
            
            r1.next = calculate(n1, n2, co)
            r1
        }     
       }
        
        calculate(l1,l2,None)
    }
}
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
import "fmt"
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
        dummyHead := new (ListNode)
        cur := dummyHead
        t := 0
        for (l1 != nil||l2 != nil||t > 0) {
            if l1 != nil {
                t += l1.Val
                l1 = l1.Next
            }
            if l2 != nil {
                t += l2.Val
                l2 = l2.Next
            }
            cur.Next = new(ListNode)
            cur = cur.Next
            cur.Val = t % 10
            t /= 10
        }
        return dummyHead.Next
}

执行结果:

posted @ 2019-08-20 17:59  ganshuoos  阅读(368)  评论(0编辑  收藏  举报