Algorithm
No.2: 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.
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
}
}
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var carry = 0, p = l1, q = l2
var dummy = ListNode(0)
var node = dummy
while p != nil || q != nil {
carry += p?.val ?? 0
carry += q?.val ?? 0
node.next = ListNode.init(carry % 10)
node = node.next!
carry = carry / 10
p = p?.next
q = q?.next
}
if carry > 0 {
node.next = ListNode.init(carry)
}
return dummy.next
}
}
Review
Swift Playgrounds in Depth(Part One)
原文: https://www.raywenderlich.com/4345-swift-playgrounds-in-depth
这篇文章讲述了一些基础性的playground使用技巧,部分已失效, 但总体还是不错的, 用来查漏补缺, 总结了以下技巧.
LiveViews.playground
Playground Page: Basic Live View
liveView的使用:
import PlaygroundSupport
PlaygroundPage.current.liveView = view
打开Assistant editor(⌥⌘Enter)就可以看到实时视图.
IndefiniteExecution.playground
Playground Page: Spring Animation
调用
PlaygroundPage.current.finishExecution()
就会直接停止执行当前页面.
Playground Page: PlaygroundLiveViewable
遵守并实现PlaygroundLiveViewable
的对象就可以被设置成为PlaygroundPage.current.liveView
IndefiniteExecution.playground
通过PlaygroundPage.current.needsIndefiniteExecution = true
来手动接管page的终止.
在使用PlaygroundPage.current.finishExecution()
来手动停止page. 注意,在当前版本的playground中(Xcode Version 10.1 (10B61))已经支持GCD的处理.
SharedPlaygroundData.playground
Playground Page: Writing to a File
playgrounds直接写文件会报错误:
Write Error: You don’t have permission to save the file
you can only write to the ~/Documents/ Shared Playground Data folder that is accessible via the playgroundSharedDataDirectory global variable in the PlaygroundSupport module.
```
在写入前, 先确保该文件夹已经存在,否则:
mkdir ~/Documents/Shared\ Playground\ Data
然后
```swift
let fileURL =
playgroundSharedDataDirectory.appendingPathComponent(filename)
Playground Page: Reading from a File
#fileLiteral(resourceName: "CoreImageFilterNames.txt") 拖到项目中后便可使用这个字面量加载文件(已失效).
Tips
Xcode10目前已经不支持直接使用Assets中素材的名字来直接创建Image Literal了, 现在可行的方案是先敲出Image
在自动联想出Image Literal
, 然后使用, 再点击出现的占位图选中自己想使用的素材, 比之前的麻烦了好多.
Share
Flutter越来越火了, 作为Native开发人员, 我觉得首先要巩固自己的护城河, 将Native 和 计算机的基础知识打牢, 然后在以开放的态度面对新技术. 同时, 在学习的时候应该多实践, 没有业务需求上的匹配, 就强制让自己造简单轮子学习.