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 is only 3 characters left in the file.
By using the read4
API, implement the function int read(char *buf, int n)
that readsn characters from the file.
Note:
The read
function will only be called once for each test case.
分析:
read函数被调用一次,那么就直接用代码解释这题即可吧。
代码:
int read4(char *buf); class Solution { public: int read(char *buf, int n) { char *cur = buf; int clen = 0, slen = 0; //当还有字符可以读出来时 while((clen = read4(cur))) { slen += clen; //当字符数目超出n时,只留下n个 if(slen >= n) { cur += n + 4 - slen; break; } cur += clen; } *cur = '