Add Two Numbers/通过链表实现加数以及进制

179 阅读1分钟

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. 解释:通过链表实现加数以及进制

public class ListNode {
    public var val: Int
    public var next: ListNode?
    public init(_ val: Int) {
        self.val = val
        self.next = nil
    }
}
extension ListNode: CustomDebugStringConvertible, CustomStringConvertible{
    public var description: String{
        var items:[Int] = [Int]()
        
        var tmp: ListNode? = self
        while tmp != nil {
            items.append(tmp!.val)
            tmp = tmp!.next
        }
        
        return "\(items)"
    }
    public var debugDescription: String{
        return "debug:\(description)"
    }
}
extension Array {
    var listNode: ListNode?{
        var node: ListNode?
        var tmp: ListNode?
        for item in self as! [Int] {
            if node == nil {
                node = ListNode.init(item)
                tmp = node
            }else{
                tmp!.next = ListNode.init(item)
                tmp = tmp?.next
            }
        }
        return node
    }
}
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
    var tmp1 = l1
    var tmp2 = l2
    var stepper = 0
    var destListNode: ListNode?
    while tmp1 != nil || tmp2 != nil {
        var dest = 0
        if(tmp1 != nil){
            dest = dest + tmp1!.val
            tmp1 = tmp1?.next
        }
        if(tmp2 != nil){
            dest = dest + tmp2!.val
            tmp2 = tmp2?.next
        }
        dest = dest + stepper
        print(dest)
        stepper = Int(dest / 10)
        if(destListNode == nil){
            destListNode = ListNode.init(dest%10)
            if tmp1 == nil && tmp2 == nil { //没有后续x且需要进位
                if stepper != 0 {
                    destListNode!.next = ListNode.init(stepper)
                }
            }
        }else{
            var tmp = destListNode
            while tmp?.next != nil {
                tmp = tmp?.next
            }
            tmp?.next = ListNode.init(Int(dest%10))
            if tmp1 == nil && tmp2 == nil { //没有后续x且需要进位
                if stepper != 0 {
                    tmp?.next?.next = ListNode.init(stepper)
                }
            }
        }
    }
   
    return destListNode
}

addTwoNumbers([2,4,3].listNode, [5,6,4].listNode)
addTwoNumbers([5].listNode, [7].listNode)
print([1,2,45,45].listNode)