题意:

解题思路:
思路:1. 循环读,循环条件判断长度是否到了n;
PHP代码实现:
/* The read4 API is defined in the parent class Reader4. public function read4(&$buf){} */class Solution extends Reader4 { /** * @param Char[] &$buf Destination buffer * @param Integer $n Number of characters to read * @return Integer The number of actual characters read */ //file-> read4 -> 4个一组,每组读完放到buf里面-> 读到n个结果,返回个数 function read(&$buf, $n) { //临时存放read4结果的数组 $tmp = []; //定义tmp指针 $index = 0; //4个一组,每组读完放到buf里 while ($index < $n) {//没有读够n个字符 //当前读到的长度 $len = $this->read4($tmp); //pointer是tmp里面的index $pointer = 0; //把tmp读到的临时数据放到buf里; //buf里的数量不足n,pointer的位置没有到len while ($index < $n && $pointer < $len) { $buf[$index] = $tmp[$pointer]; $index++; $pointer++; } //已经读完file.ex filr "abcde", n = 6 if ($len < 4) break; } return $index; }}
GO代码实现:
/** * The read4 API is already defined for you. * * read4 := func(buf []byte) int * * // Below is an example of how the read4 API can be called. * file := File("abcdefghijk") // File is "abcdefghijk", initially file pointer (fp) points to 'a' * buf := make([]byte, 4) // Create buffer with enough space to store characters * read4(buf) // read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e' * read4(buf) // read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i' * read4(buf) // read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file */var solution = func(read4 func([]byte) int) func([]byte, int) int { // implement read below. return func(buf []byte, n int) int { tmp := make([]byte, 4) index := 0 for index < n { len := read4(tmp) pointer := 0 for index < n && pointer < len { buf[index] = tmp[pointer] index++ pointer++ } if len < 4 { break } } return index }}