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)
readsn characters from the file.
Note:
The function is only being read
called once for each test case.
Analysis:
The read function is called once, so you can explain the problem directly in code.
Code:
intREAD4 (Char*buf);classSolution { Public: intReadChar*buf,intN) {Char*cur =buf; intClen =0, Slen =0; //When there are characters that can be read out, while((Clen =read4 (cur))) {Slen+=Clen; //when the number of characters exceeds n, only n is left if(Slen >=N) {cur+ = n +4-Slen; Break; } cur+=Clen; } *cur =' /'; //When the number of characters is less than n, the file is read, the total length of the file is returned, and if the number of characters is greater than or equal to N, n returnSlen < n?slen:n; }};
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.
By using the Read4 API, implement the function int. read (char *buf, int n) that reads n characters from the file.
Note:
The read function may be called multiple times.
Analysis:
Compared to I, this question to be called multiple times, and a large number of file read operation time is very expensive, in order to solve this problem, you can use a cache to store the characters that have been read, I use a private string as a cache.
Code:
intREAD4 (Char*buf);classSolution {Private: stringstr; Public: Solution () {str=""; } intReadChar*buf,intN) {//use cache to remove unnecessary operations if(N <=str.length ()) { //passing a string to an array of stringsstrncpy (buf, Str.c_str (), n); returnN; } strcpy (buf, Str.c_str ()); Char*cur = buf +str.length (); intClen =0, Slen =int(Str.length ()); //continue to read characters in the file when the cache is not sufficient while((Clen =read4 (cur))) {Slen+=Clen; //when the number of characters exceeds n, only n is left if(Slen >=N) {str.append (cur, n+4-Slen); Cur+ = n +4-Slen; Break; } //array of strings passed to stringstr.append (cur, clen); Cur+=Clen; } *cur =' /'; //When the number of characters is less than n, the file is read, the total length of the file is returned, and if the number of characters is greater than or equal to N, n returnSlen < n?slen:n; }};
Note: The subject code is not validated
[Locked] Read n characters Given Read4 & read n characters Given Read4 ii-call multiple times