158 Read N Characters Given Read4 II - Call multiple times
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 theread4
API, implement the functionint read(char *buf, int n)
that readsncharacters from the file.
Note:
Theread
function may be called multiple times.
Example 1:
Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""
Example 2:
Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""
Understand the diff between 1 and 2
/* 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 tempPtr = 0;
private int count = 0;
private char[]temp = new char[4]; //global array
public int read(char[] buf, int n) {//READ MULTIPLE TIMES, MEANS EVERYTIME, INDEX = 0 AND WRITE TO BUF
int index = 0;
while (index < n) {
if (tempPtr == 0) {//temp is empty
count = read4(temp);//use counter to count
}
if (count == 0) {
break;//nothing to read
}
//write
while (index < n && tempPtr < count) {
buf[index++] = temp[tempPtr++];
}
if (tempPtr == count ){//means you have written everything from temp to buf
tempPtr = 0;
}
}
return index;
}
}