/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
}
};
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int res = 0;
for (int i = 0; i < n; i += 4) {
res += read4(buf); //指针后移
buf += 4;
}
return min(res, n);
}
};
"""
The read4 API is already defined for you.
@param buf4, a list of characters
@return an integer
def read4(buf4):
# 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'
buf4 = [' '] * 4 # Create buffer with enough space to store characters
read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""
class Solution:
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
bi = 0
for _ in range(0, n, 4):
tmp = [None] * 4 #必须先开辟出4个空间
cur_len = read4(tmp) #先读入到tmp
for j in range(cur_len):
buf[bi] = tmp[j] #从tmp复制到buf
bi += 1
return min(bi, n)
/**
* The read4 API is already defined for you.
*
* read4 := func(buf4 []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'
* buf4 := make([]byte, 4) // Create buffer with enough space to store characters
* read4(buf4) // read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
* read4(buf4) // read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
* read4(buf4) // 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 {
idx := 0
tmp := make([]byte, 4)
for {
cnt := read4(tmp)
for j := 0; j < cnt; j, idx = j + 1, idx + 1 {
buf[idx] = tmp[j]
}
if cnt < 4 {
break
}
}
if n < idx {
return n
}
return idx
}
}
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf);
*/
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
int index = 0;
char[] temp = new char[4];
while (index < n) {
int count = read4(temp);
if (count == 0) {
break;
}
for (int i = 0; i < count; i++) {
buf[index + i] = temp[i];
}
index += count;
}
return Math.min(index, n);
}
}