Thinking process

The real meaning of this question is to read characters from a file and save them into the buffer.

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {

        char[] tmpBuf = new char[4];
        int index = 0;
        boolean isEnd = false;

        while (!isEnd && index < n) {
            int readChars = read4(tmpBuf);

            if (readChars != 4) {
                isEnd = true;
            }

            readChars = Math.min(n - index, readChars);
            for (int i = 0; i < readChars; ++i) {
                buf[index + i] = tmpBuf[i];
            }

            index += readChars;
        }


        return index;
    }
}

158

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    private char[] tmpBuf = new char[4];
    private boolean endOfFile = false;
    private int offset = 0;
    private int remaining = 0;
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        int currIndex = 0;
        while ((!endOfFile || remaining > 0) && n > currIndex) {
            int readChars = 0;
            if (remaining != 0) {
                readChars = remaining;
            } else {
                offset = 0;
                readChars = read4(tmpBuf);

                if (readChars != 4) {
                    endOfFile = true;
                }
            }

            int length = Math.min(n - currIndex, readChars);
            for (int i = offset; i < offset + length; ++i) {
                buf[currIndex++] = tmpBuf[i];
            }

            remaining = readChars - length;
            if (remaining != 0) {
                offset += length;
            }
        }

        return currIndex;
    }
}

results matching ""

    No results matching ""