> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/google/157-read-n-characters-given-read4.md).

# 157 Read N Characters Given Read4

## 157. [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/description/)

## 1. Question

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 readsncharacters from the file.

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

## 2. Implementation

思路: 这题要我们利用一个已有的函数read4()实现一个自定义的函数read(), 和read4()不同的是，read()里有一个参数n，定义我们读多少byte的数据，而read4()只会一次读4个byte。这里主要的考点是edge cases. **如果read4返回的值是小于4，说明是end of file**。同时为了**保证我们读取不超过 n个byte的数据**，每次将数据copy到buffer时，我们都要取n - index和size之间较小的那个数。

```java
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        boolean eof = false;
        char[] buffer = new char[4];
        int index = 0;
        while (!eof && index < n) {
            int size = read4(buffer);
            if (size < 4) {
                eof = true;
            }
            int bytes = Math.min(n - index, size);  
            for (int i = 0; i < bytes; i++) {
                buf[index++] = buffer[i];
            }
        }
        return index;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)
