一、前言
又是阳光灿烂的一天,那就废话不多说,开始今天的刷题。
二、Problem
Add Two Numbers
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
问题的意思也很浅显易懂,给两个链表,计算它们相加之后的值。
三、Solution
思路的话也蛮简单的,链表的每一个节点分别相加,将进位传到下一个节点。如果两个链表长度不一样,则给短的补零,使它们长度一样。
代码如下:
//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 addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var carry = 0
var list1 = l1
var list2 = l2
var list3: ListNode? = ListNode(0)
var node = list3
while list1 != nil || list2 != nil {
let list1Vaule = list1?.val != nil ? list1!.val : 0
let list2Vaule = list2?.val != nil ? list2!.val : 0
node?.next = ListNode((list1Vaule + list2Vaule + carry) % 10)
node = node?.next
carry = (list1Vaule + list2Vaule + carry) / 10
list1 = list1?.next
list2 = list2?.next
}
if (carry > 0) {
node?.next = ListNode(carry)
}
list3 = list3?.next
return list3
}
}
开始我没有考虑到最后一次进位的情况,也就是以下代码没写
if (carry > 0) {
node?.next = ListNode(carry)
}
然后提交之后,LeetCode报了一个Wrong Answer的错
可以说是非常人性了。但在平时自己写代码的过程中我们还是要尽可能多的考虑情况,毕竟那时候没人会提醒你了。话说我觉得这个算法可以用来解决两个超大数的相加,你觉得呢?
惯例放上GitHub地址:https://github.com/BreadAwesome/LeetCode-Swift
网友评论