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.

Solution

/* 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
     */

    char[] buf4 = new char[4];

    int pls = 0; // buf4 reading place
    int len = 0; // buf4 valid length

    boolean end = false;

    public int read(char[] buf, int n) {
        int cnt = 0;
        while(n > 0) {
            if(pls == len) {
                // no remaining chars in buf4, need to read more
                if(end) break;

                len = read4(buf4);
                pls = 0;

                end = len < 4;
            }

            while(pls < len && n-- > 0) {
                buf[cnt++] = buf4[pls++];
            }
        }

        return cnt;
    }
}

results matching ""

    No results matching ""