157. 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) {
        int tmp, k = 0;
        char buf4[4];
        while (k < n) {
            tmp = read4(buf4);
            for (int i = 0; i < tmp && k < n; i++)
                buf[k++] = buf4[i];
            if (tmp < 4) break;
        }
        return k;
    }
};

results matching ""

    No results matching ""