Elegant and simple Java code, checked the case that n > buf.length


  • 0
    B
    private char[] tmp = new char[4];
        private int start = 4;
        private int end = 4;
        public int read(char[] buf, int n) {
            int count = 0;
            if (n > buf.length) n = buf.length; //reduce n if buf.length < n
            while (count < n) {
                if (start == end) { //read 4 chars to tmp
                    end = read4(tmp);
                    start = 0;
                    if (end == 0) break; //if (end == 0) break;
                }
                while (start < end && count < n) { //read chars from tmp to buf
                    buf[count++] = tmp[start++];
                }
            }
            return count;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.