Java Solution using arraycopy


  • 0
    D
        public int read(char[] buf, int n) {
            for(int i = 0; i < n; i += 4){
                char[] tmp = new char[4]; 
                 // use an array to store the characters read
                int len = read4(tmp);
                // Store the number of characters being read in an array
                System.arraycopy(tmp, 0, buf, i, Math.min(len, n - i));
                // copy characters in the array to the buffer. The length is the min value betwee len and remainingspaces in the array
                if(len < 4) return Math.min(i + len, n);
                // If the characters being read is less than 4, return the min value of  i+len and n
            }
            return n;
        }

Log in to reply
 

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