@@ -0,0 +1,2111 @@
+package com.freetymekiyan.algorithms.level.easy;%0A%0A/**%0A * The API: int read4(char *buf) reads 4 characters at a time from a file.%0A * %3Cp%3E%0A * The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters%0A * left in the file.%0A * %3Cp%3E%0A * By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.%0A * %3Cp%3E%0A * Note:%0A * The read function will only be called once for each test case.%0A * %3Cp%3E%0A * Company Tags: Facebook%0A * Tags: String%0A * Similar Problems: (H) Read N Characters Given Read4 II - Call multiple times%0A */%0Apublic class ReadNCharactersGivenRead4 %7B%0A%0A    /*%0A     * The read4 API is defined in the parent class Reader4.%0A     * int read4(char%5B%5D buf);%0A     */%0A    public class Solution extends Reader4 %7B%0A%0A        /**%0A         * Read with read4 to an intermediate buffer.%0A         * Every time check if we reach the end of the file.%0A         * If read4 returns size smaller than 4, it means end of file.%0A         * Copy characters in read4 buffer to output buffer.%0A         * Update readBytes.%0A         *%0A         * @param buf Destination buffer%0A         * @param n   Maximum number of characters to read%0A         * @return The number of characters read%0A         */%0A        public int read(char%5B%5D buf, int n) %7B%0A            int readBytes = 0;%0A            char%5B%5D buffer = new char%5B4%5D;%0A            int bufPointer = 0;%0A            int bufCounter = 0;%0A%0A            while (readBytes %3C n) %7B%0A                if (bufPointer == 0) %7B%0A                    bufCounter = read4(buffer);%0A                %7D%0A                if (bufCounter == 0) %7B%0A                    break;%0A                %7D%0A                while (readBytes %3C n && bufPointer %3C bufCounter) %7B%0A                    buf%5BreadBytes++%5D = buffer%5BbufPointer++%5D;%0A                %7D%0A                if (bufPointer == bufCounter) %7B%0A                    bufPointer = 0;%0A                %7D%0A            %7D%0A            return readBytes;%0A        %7D%0A    %7D%0A%0A    /**%0A     * Dummy%0A     */%0A    private class Reader4 %7B%0A%0A        int read4(char%5B%5D buf) %7B%0A            return 0;%0A        %7D%0A    %7D%0A%7D%0A

update read n characters given read 4