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多條,我覺得應(yīng)該是題意太confusing了。我一開始以為buf是要讀的文件,后來想想不太對。讀了一下@param, 原來buf是Destination buffer,學(xué)過IO應(yīng)該才會懂,這個是讓我們把file讀到buffer里面去。所以我們讀的時候要寫到buf里,同時要返回讀過的character數(shù)目。我剛開始還是很confused, 心想既然都告訴了我們讀n個,那直接返回n不就好了。然而文件總char數(shù)可能是小于n的,這種情況就不能直接返回n.
幾個要點(diǎn):
- 這題沒有給input file, 要抽象讀取這個過程,把重點(diǎn)放到計算讀過的字符數(shù)和寫入buf這里。
- 每次讀4個,并且保存到一個臨時的char array內(nèi),然后再復(fù)制到buf里。注意這里復(fù)制的長度不能直接寫4. 有幾種情況需要考慮:
- 不需要讀完這4個字符串就已經(jīng)達(dá)到總數(shù)n了,那么我們只需要復(fù)制n - i個就行,所以我們這里是復(fù)制Math.min(len, n - i)個;
- len < 4, 說明這時候其實已經(jīng)讀到文件尾部了,這時候copy len個就好,而且這種情況我們其實已經(jīng)可以直接返回了,讀的字符數(shù)為i + len個。這個時候還得考慮是不是已經(jīng)讀了n個,如果已經(jīng)到了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;
}
}