Leetcode 157. 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.

思路:文件中的字符数可能小于n,所以不断借助read4读取字符的时候需要判断是否已经读到文件末尾。每次将read4中字符复制到buf中时,也需要判断好能够复制的上限。

public int read(char[] buf, int n) {
    if (n <= 0) {
        return 0;
    }

    char[] buf4 = new char[4];
    int total = 0;
    boolean eof = false;

    while (!eof && total < n) {
        int read4Cnt = read4(buf4);
        eof = read4Cnt < 4;

        int copyCnt = Math.min(read4Cnt, n - total);
        for (int i = 0; i < copyCnt; i++) {
            buf[total++] = buf4[i];
        }
    }

    return total;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/b06b90a52617
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞