Read N Characters Given Read4

Problem: Read N Characters Given Read4

If n is bigger than 4, than we do read4 repeatedly. If smaller, we read smaller numbers of characters and do corresponding modification on pointer to destination buffer.

Code in C++:

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 res = 0;
        while (n > 0) {
            int tmp = min(read4(buf), n);
            res += tmp;
            buf += tmp;
            if (tmp < 4)
                break;
            n -= 4;
        }
        return res;
    }
};

results matching ""

    No results matching ""