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.
READ4 (char[] buf) refers to reading 4 numbers, storing them in buf, and then returning the number of successful reads, if not enough four, then returns the remaining number of characters.
The implemented read (char[] buf, int n) functions Similarly, except that 4 is changed to N, which requires input. (Here is an example that reads only once)
When I first started, I understood that it was wrong to read the characters in the buf, causing the commit to fail.
The method is: first read N/4 times read4, if there is a case of not equal to 4, then return the result.
And then read the last time, need to judge is: 1, if just finished reading, directly return the results
2, judge the size of N-result and read num, select Small, read and return the number.
/*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) {if(N < 1){ return0; } intTime = N/4; intresult = 0; Char[] chars =New Char[4]; for(inti = 0; I < time; i++){ intnum =read4 (chars); for(intj = 0; J < num; J + +) {Buf[i* 4 + j] =Chars[j]; } if(Num! = 4) {result+=num; returnresult; } Else{result+ = 4; } } if(N-result = = 0){ returnresult; } intnum =read4 (chars); for(inti = 0; I < Math.min (N-result, num); i++) {Buf[result+ i] =Chars[i]; } result+ = Math.min (N-result, num); returnresult; }}
Leetcode 157. Read N characters Given READ4 implements read---------Java
using READ4