LeetCode 2. Add Two Numbers swift
// // main.swift // leetcode02 // // Created by GuoLa on 16/1/21. // Copyright © 2016年 GuoLa. All rights reserved. // import Foundation func input() -> String { let keyboard = NSFileHandle.fileHandleWithStandardInput() let inputData = keyboard.availableData let strData = NSString(data: inputData, encoding: NSUTF8StringEncoding)! return strData.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) } class ListNode{ var val:Int var next:ListNode? init(_ num: Int) { val=num next=nil } func desc()->String{ var ret:String = String(val) var node = next while node != nil { ret = ret.stringByAppendingFormat("->%d", (node?.val)!) node=node!.next } return ret } } public class SolutionAddTwoNumbers{ func addTwoNumbers(l1: ListNode?,l2: ListNode?) ->ListNode{ let ret:ListNode = ListNode(-1) var p1=l1 var p2=l2 var p:ListNode = ret if l1 == nil { ret.next = l2; return ret;} if l2 == nil { ret.next = l1; return ret;} var p1count = 0 while p1 != nil { p1=p1?.next p1count++ } var p2count = 0 while p2 != nil { p2=p2?.next p2count++ } if p2count > p1count { p1=l2 p2=l1 }else { p1=l1 p2=l2 } while p1 != nil { if p2 == nil { var sum=p1!.val if p.next != nil { sum+=(p.next!.val); } p.next=ListNode(sum%10) p=p.next! if sum/10 > 0 { p.next = ListNode(1) } p1=p1?.next } while p2 != nil { var sum=p1!.val+p2!.val if p.next != nil { sum+=(p.next!.val); } p.next=ListNode(sum%10) p=p.next! if sum/10 > 0 { p.next = ListNode(1) } p1=p1!.next p2=p2!.next } } return ret.next!; } } func ListNodeCreate(str: String) ->ListNode { let str:[String] = str.componentsSeparatedByString("->") var list:ListNode = ListNode(-1) let ret = list for s in str { list.next = ListNode(Int(s)!) list=list.next! } return ret.next! } var testCaseAddTowNumber = SolutionAddTwoNumbers() var l1:String = "" repeat{ print("Enter ListNode1:(Input exit,Program end!)") //var l1 = "2->3->4" l1 = input() if l1 == "exit" {break} print("Enter ListNode2:") //var l2 = "1->2->3" var l2 = input() let nodel1 = ListNodeCreate(l1) let nodel2 = ListNodeCreate(l2) print(nodel1.desc()) print(nodel2.desc()) var tow = SolutionAddTwoNumbers() var ret = tow.addTwoNumbers(nodel1, l2: nodel2) print(ret.desc()) } while l1 != "exit"
测试输入
1->8
0
结果:1->8
0
7->3
结果 7->3
3
4->2
结果:7 2
6
4->2
结果:0 3
3->4->5
1->2->3
结果:4->6->8
9->4->5
1->2->3
结果:0->7->8
3->8->5
1->2->3
结果:4->0->9
3->4->7
1->2->3
结果:4->6->0->1