[Swift]LeetCode157.用Read4来读取N个字符 $ Read N Characters Given Read4
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10060469.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.
API:int Read 4(char *BUF)每次从一个文件读取4个字符。
返回值是读取的实际字符数。例如,如果文件中只剩下3个字符,则返回3。
通过使用read4 API,实现从文件中读取n个字符的int read(char*buf,int n)函数。
注:
读取函数只对每个测试用例调用一次。
1 class Solution { 2 func read(_ buf:[Character],_ n:Int) -> Int { 3 var res:Int = 0 4 for i in 0...n 5 { 6 var cur:Int = read4(buf + res) 7 if cur == 0 {break} 8 res += cur 9 } 10 return min(res, n) 11 } 12 }