Read N characters given read4

https://leetcode.com/problems/read-n-characters-given-read4/

// 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) 
    {
        char tmp[4];
        int cur_pos = 0;
        int total_pos = 0;

        for(int i = 0; i<n; i++)
        {
            if(cur_pos == total_pos)
            {
                total_pos = read4(tmp);
                cur_pos = 0;
            }

            if(cur_pos < total_pos)
            {
                buf[i] = tmp[cur_pos++];
            }
            else
            {
                return i;
            }
        }

        return n;
    }
};

results matching ""

    No results matching ""