Easy
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.
这道题downvote有300多条,我觉得应该是题意太confusing了。我一开始以为buf是要读的文件,后来想想不太对。读了一下@param, 原来buf是Destination buffer,学过IO应该才会懂,这个是让我们把file读到buffer里面去。所以我们读的时候要写到buf里,同时要返回读过的character数目。我刚开始还是很confused, 心想既然都告诉了我们读n个,那直接返回n不就好了。然而文件总char数可能是小于n的,这种情况就不能直接返回n.
几个要点:
- 这题没有给input file, 要抽象读取这个过程,把重点放到计算读过的字符数和写入buf这里。
- 每次读4个,并且保存到一个临时的char array内,然后再复制到buf里。注意这里复制的长度不能直接写4. 有几种情况需要考虑:
- 不需要读完这4个字符串就已经达到总数n了,那么我们只需要复制n - i个就行,所以我们这里是复制Math.min(len, n - i)个;
- len < 4, 说明这时候其实已经读到文件尾部了,这时候copy len个就好,而且这种情况我们其实已经可以直接返回了,读的字符数为i + len个。这个时候还得考虑是不是已经读了n个,如果已经到了n个,就直接返回n,所以我们返回的是Math.min(n, i + len).
/* 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 Maximum number of characters to read
* @return The number of characters read
*/
public int read(char[] buf, int n) {
//possible cases:
//there's more than n characters in the file, return n
//there's less than n characters in the file, use API to determine how many we read
for (int i = 0; i < n; i += 4){
char[] temp = new char[4];
int len = read4(temp);
System.arraycopy(temp, 0, buf, i, Math.min(len, n - i));
if (len < 4){
return Math.min(i + len, n);
}
}
return n;
}
}