Read N Characters Given Read4

来源:互联网 发布:淘宝可以申请几个小号 编辑:程序博客网 时间:2024/05/29 14:34

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.

API read4 返回所读字符的长度,可能是4,也可能比4小。调用read4 API 时需要传入char数组且长度为4.

read函数 返回所读字符的长度,也许是n,也许比n 小

public int read(char[] buf, int n) {        int cnt = 0;        char[] tmp = new char[4];        while (cnt < n) {            int len = read4(tmp);            if (len == 0) break;            int idx = 0;            while (cnt < n && idx < len) buf[cnt++] = tmp[idx++];        }        return cnt;    }



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.

注意 : read 函数 可以被调用多次

因为要被调用多次, 每次 tmp_ptr 到达 len 的长度时要被清零。

    char[] tmp = new char[4];    int tmp_ptr = 0;    int len = 0;    public int read(char[] buf, int n) {        int ptr = 0;        while (ptr < n) {            if (tmp_ptr == 0) {                len = read4(tmp);            }            if (len == 0) break;            while (ptr < n && tmp_ptr < len) {                buf[ptr++] = tmp[tmp_ptr++];            }            if (tmp_ptr == len) tmp_ptr = 0;        }        return ptr;    }










原创粉丝点击