Short and elegant 10-line java solution


  • 0
    V
    /* 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) {
            char[] tmp = new char[4];
            int bufIndex = 0, curCount = 0;
            while (bufIndex < n && (curCount = read4(tmp)) > 0) {
                int copyCount = Math.min(curCount, n - bufIndex);
                for(int i = 0; i < copyCount; i++) {
                    buf[bufIndex++] = tmp[i];
                }
            }
            return bufIndex;
        }
    }

Log in to reply
 

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