1. 程式人生 > >[Swift]LeetCode158. 用Read4來讀取N個字元II $ Read N Characters Given Read4 II

[Swift]LeetCode158. 用Read4來讀取N個字元II $ Read N Characters Given Read4 II

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 may be called multiple times.


API:int Read 4(char *BUF)每次從一個檔案讀取4個字元。

返回值是讀取的實際字元數。例如,如果檔案中只剩下3個字元,則返回3。

通過使用read4 API,實現從檔案中讀取n個字元的int read(char*buf,int n)函式。

注:

讀取函式可以被多次呼叫。


 1 class Solution {
 2     var readPos:Int = 0
 3     var writePos:Int = 0
 4     var
buff:[Character] = [Character](repeating:" ",count:4) 5 func read(_ buf:[Character],_ n:Int) -> Int { 6 var i:Int = 0 7 while (i < n && (readPos < writePos || (readPos = 0) < (writePos = read4(buff)))) 8 { 9 buf[i] = buff[readPos]
10 i += 1 11 readPos += 1 12 } 13 return i 14 } 15 }