先说1;
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.
当读的时候会有以下三种情况。
1. 所需要的个数比读进来的树要少。比如文件是abc,但是我想读两个字节。所以这个时候,返回值返回的就不能是你读的个数,而是你所需要的个数。
2. 读进来的数少于4个,这种情况下read4的返回值再加上之前的值就可以了。
3. 一读读进来4个,那就继续读下去。
其实(2,3可以合并)
代码如下:
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
int read(char *buf, int n) {
int result = 0;
while (n > 0) {
int numread = read4(buf);
if (numread >= n) {
result += n;
return result;
}
if (numread < 4) {
result += numread;
break;
}
n -= numread;
result += numread;
buf += numread;
}
return result;
}
};
再说2
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.
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
private:
list<char> buff;
public:
int read(char *buf, int n) {
if (n <= 0)
return 0;
if (!buff.empty()) {
int idx = 0;
while (n > 0 && !buff.empty()) {
*buf = buff.front();
buff.pop_front();
idx++;
n--;
buf++;
}
return read(buf,n)+idx;
}
int result = 0;
while (n > 0) {
int numread = read4(buf);
if (numread >= n) {
result += n;
for (int i = 0; i < numread-n; i++) {
buff.push_back(*(buf+n+i));
}
return result;
}
if (numread < 4) {
result += numread;
break;
}
n -= numread;
result += numread;
buf += numread;
}
return result;
}
};