## 157. Read N Characters Given Read4 - Only calling one time

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.

Example 1:

``````Input:
buf ="abc", n = 4

Output:
"abc"

Explanation: The actual number of characters read is 3, which is "abc".
``````

Example 2:

``````Input: buf = "abcde", n = 5

Output: "abcde"
``````

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

Thoughts:

1. Having a position counter: end to keep track the current reading position
2. return the min of end and the n: min(end,n)
``````// Forward declaration of the read4 API.

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 end = 0, lastRead = 4;  // end position returned by read4, lastnumber of chars read
while(end < n && lastRead == 4){
}

return min(end, n);
}
};
``````
``````/* The read4 API is defined in the parent class Reader4.

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) {
int end = 0; char[]tmp = new char;
while(end < n){
int stop = Math.min(end + count, n);
for (int i = end; i < stop; i++)
buf[i] = tmp[i - end];
end = stop;
if(count < 4) return end;
}

return end;
}
}
``````