November 20, 2019

158. Read N Characters Given Read4 II - Call multiple times

158. Read N Characters Given Read4 II - Call multiple times

参考了这个帖子.

/**
 * 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   Number of characters to read
     * @return    The number of actual characters read
     */
    private int buffPtr = 0;
    private int buffCnt = 0;
    private char[] buff = new char[4];    
    
    public int read(char[] buf, int n) {
        int count = 0;
        while (count < n) {
            if (buffPtr == buffCnt) {
                int read4 = read4(buff);
                if (read4 == 0) {
                    break;
                }
                buffPtr = 0;
                buffCnt = read4;
            }
            while (count < n && buffPtr < buffCnt) {
                buf[count++] = buff[buffPtr++];
            }
        }
        return count;
    }
}
comments powered by Disqus