Leetcode 158 Solution

This article provides solution to leetcode question 158 (read-n-characters-given-read4-ii-call-multiple-times)

https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times

Solution

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n)
    {
        int i = 0;
        while( i < n ){
            if( readPos == writePos ){
                writePos = read4( reserved );
                readPos = 0;

                if( !writePos )
                    return i;
            }

            buf[i++] = reserved[readPos++];
        }

        return i;
    }

private:
    int readPos = 0;
    int writePos = 0;
    char reserved[4];
};