Read N characters Given Read4
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.
1 //Forward Declaration of the Read4 API.2 intREAD4 (Char*buf);3 4 classSolution {5 Public:6 /**7 * @param buf Destination buffer8 * @param n Maximum number of characters to read9 * @return The number of characters readTen */ One intReadChar*buf,intN) { A Chartmp[4]; - intIDX =0, Cnt4; - while(IDX <N) { theCNT4 =READ4 (TMP); - for(inti =0; I < cnt4 && idx < n; ++i) { -buf[idx++] =Tmp[i]; - } + if(Cnt4 <4) Break; - } + returnidx; A } at};
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 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 read
function may be called multiple times.
1 //Forward Declaration of the Read4 API.2 intREAD4 (Char*buf);3 4 classSolution {5 Private:6 Chartmp[4];7 intTmp_idx =0, Tmp_len =0;8 Public:9 /**Ten * @param buf Destination buffer One * @param n Maximum number of characters to read A * @return The number of characters read - */ - intReadChar*buf,intN) { the intIDX =0; - BOOLFlag; - while(IDX <N) { -Flag =true; + if(Tmp_idx = =Tmp_len) { -Tmp_idx =0; +Tmp_len =READ4 (TMP); A if(Tmp_len! =4) flag =false; at } - for(; tmp_idx < Tmp_len && idx < n; + +tmp_idx) { -buf[idx++] =Tmp[tmp_idx]; - } - if(!flag) Break; - } in returnidx; - } to};
[Leetcode] Read N characters Given Read4 I & II