157. Read N Characters Given Read4
Problem description:
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.
Example 1:1
2
3Input: buf = "abc", n = 4
Output: "abc"
Explanation: The actual number of characters read is 3, which is "abc".
Example 2:1
2Input: buf = "abcde", n = 5
Output: "abcde"
Note:
The read function will only be called once for each test case.
Solution:
Question to ask:
- read4 can be use multiple times?
- output type
One thing to notice is that the read
will only be called once. The read4
will return how many characters it read from the input char *buf
. So we can use a variable to cumulate the sum of characters that read by read4
. Once the return value of read4
is smaller than 4, that means we reached the last position.
Make sure to move the position in char *buf
for read4
to read next position.
1 | // Forward declaration of the read4 API. |
time complexity: $O(n)$
space complexity: $O(1)$
reference: