这是一个链表问题:
输入:2 -> 4 -> 3
和5 -> 6 -> 4
预期708
因为342 + 465 = 708
让我感到困惑的是:
result = result!.next
在函数toList()
result.next是一个类,一个引用类型,但是当我将其设置为result时,它就像一个右值,result
的值类型为nil
。为什么以及如何解决?
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func toInt(_ l: ListNode?) -> Int {
var power = 1, result = 0, curr = l
while curr != nil {
result += power * curr!.val
curr = curr!.next
power *= 10
}
// print("\(result)")
return result
}
func toList(_ i: Int) -> ListNode? {
var result: ListNode? = nil, num = i
while num != 0 {
result = ListNode(num % 10)
result = result!.next
num /= 10
}
return result
}
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
return toList(toInt(l1) + toInt(l2))
}
}
答案 0 :(得分:-1)
尝试一下:
func toList(_ i: Int) -> ListNode? {
var result: ListNode? = ListNode(i % 10), num = i / 10
while num != 0 {
let nextResult = ListNode(num % 10)
result!.next = nextResult
result = result!.next
num /= 10
}
return result
}