# Problem 157: Read N Characters Given Read4

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

![](https://1241747088-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lpv9LvBSlFaukf_ALqh%2F-Lpv9NPw3Ji1X5Vk8CES%2F-LpvA-1kPHD1J5w9z-Ic%2F157.png?generation=1569729545241430\&alt=media)

## 思路

* read4() 每次读取的元素是 4 个。如果 n 可以被 4 整除，那么正好读完；如果不能被 4 整除，那么就需要在 n 的时候截止。

```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) {
        char[] buf4 = new char[4];
        int count = 0;
        while (true) {
            int size = read4(buf4);
            for (int i = 0; i < size && count < n; i++) {
                buf[count++] = buf4[i];
            }

            if (size == 0 || count == n) {
                return count;
            }
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://liuyang89116.gitbook.io/my-leetcode-book/post_chapter_3_array/problem_157_read_n_characters_given_read4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
