Read N Characters Given Read 4

Leetcode 157

/* 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
     */
    public int read(char[] buf, int n) {    
        int k = 4;
        int tot = 0;
        char[] tmp = new char[4];
        while(k==4) {
            k = read4(tmp);            
            for(int i=0;i<Math.min(k,n);i++) {
                buf[tot++] = tmp[i];
            }
            n -= k;
            if(n<=0) break;
        }
        return tot;
    }
}

Call multiple times:

Last updated