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 are only 3 characters left in the file.
read4
by using the API, implement the function that int read(char *buf, int n)
reads n characters from the file.
Note:
The function is only being read
called once for each test case.
Problem Solving Ideas:
start to understand the test instructions error, read 4 characters each time, not read from the BUF, but read from the file, deposited into BUF. If Read4 < 4, the end of the file is read. At the same time think of File.length > N, each time you want to determine the correct length to read into the BUF, that is max.min (count, N-total)
Java Code:
/*The read4 API is defined in the parent class Reader4. int Read4 (char[] buf); */ Public classSolutionextendsReader4 {/** * @parambuf Destination Buffer *@paramn Maximum number of characters to read *@returnThe number of characters read*/ Public intReadChar[] buf,intN) {BooleanEOF =false;//End of File Char[] temp =New Char[4]; intTotal = 0; while(!eof && Total <N) { intCount =read4 (temp); if(Count < 4) {EOF=true; } //get the actual countCount = Math.min (count, N-Total ); for(inti = 0; i< count; i++) {Buf[total++] =Temp[i]; } } returnTotal ; }}
Reference:
1. Https://leetcode.com/discuss/44743/another-accepted-java-solution
2. http://bangbingsyb.blogspot.com/2014/11/leetcode-read-n-characters-given-read4.html
Leetcode Read N characters Given Read4