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)
}
}
执行结果: