Wednesday, July 31, 2019

Leetcode 157: Read N Characters Given Read4

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

The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read.

For example, it returns 3 if there is only 3 characters left in the file. By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function will only be called once for each test case.

Notes:

This question seems very confusing, but actually it is not a hard problem at all.

The buf is the pointer pointing to the current reading position. We can use a variable to record the total number of char read so far. When it reaches n or no more char left in the file, we should stop the loop.

See the code below:

class solution {
public:
    int read(char *buf, int n) {
        int res = 0;//total number of char read so far;
            while(res < n) {
                int cur = read4(buf + res);//number of chars read from read4 API;
                res += cur;
                if(cur < 4) break;//no more char left;
            }
        return min(res, n);
    }
};

No comments:

Post a Comment