Having a read4 index to indicate when to read, keep track the index until either the returned value from API is 0 or n is reached
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
private:
char buf4[4];
int buf4Index = 4;
int buf4Size = 4;
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 i = 0;
while(i < n){
// check calling API condition
if(buf4Index >= buf4Size){
buf4Size = read4(buf4);
if(buf4Size == 0) break;
buf4Index = 0;
}
buf[i] = buf4[buf4Index];
i++;
buf4Index++;
}
return i;
}
};
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
*/
private int ptr = 0;
private int count = 0;
private char[] buff = new char[4];
public int read(char[] buf, int n) {
int i = 0;
while (i < n) {
if (ptr == 0) {
count = read4(buff);
}
if (count == 0) break;
while (i < n && ptr < count) {
buf[i++] = buff[ptr++];
}
if (ptr >= count) ptr = 0;
}
return i;
}
}