您的位置:首页 > 其它

[LeetCode] Read N Characters Given Read4 I & II

2015-09-06 11:33 232 查看
Read N Characters Given Read4

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.

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
/**
* @param buf Destination buffer
* @param n   Maximum number of characters to read
* @return    The number of characters read
*/
int read(char *buf, int n) {
char tmp[4];
int idx = 0, cnt4;
while (idx < n) {
cnt4 = read4(tmp);
for (int i = 0; i < cnt4 && idx < n; ++i) {
buf[idx++] = tmp[i];
}
if (cnt4 < 4) break;
}
return idx;
}
};


Read N Characters Given Read4 II - Call multiple times

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:
char tmp[4];
int tmp_idx = 0, tmp_len = 0;
public:
/**
* @param buf Destination buffer
* @param n   Maximum number of characters to read
* @return    The number of characters read
*/
int read(char *buf, int n) {
int idx = 0;
bool flag;
while (idx < n) {
flag = true;
if (tmp_idx == tmp_len) {
tmp_idx = 0;
tmp_len = read4(tmp);
if (tmp_len != 4) flag = false;
}
for (; tmp_idx < tmp_len && idx < n; ++tmp_idx) {
buf[idx++] = tmp[tmp_idx];
}
if (!flag) break;
}
return idx;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: