/** * The read4 API is defined in the parent class Reader4. * int read4(char *buf4); */
classSolution { public: /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ intread(char *buf, int n){ int cnt = 0; while (b != e && cnt < n) { buf[cnt++] = buf4[b++]; } if (cnt == n) return cnt; b = 0; // cnt不等于n,说明b == e,重置b,更新e读新字符 e = read4(buf4); if (e == 0) return cnt; return cnt + read(buf + cnt, n - cnt); }
// Forward declaration of the read4 API. intread4(char *buf);
classSolution { public: /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ intread(char *buf, int n){ int cnt = 0; while (i < e && cnt < n) { // 在全局buffer的边界之内尽可能多的读字符 buf[cnt++] = t[i++]; } if (i == e) i = e = 0; // 如果全局buffer里到边界的所有字符都被读走,则重置下标和边界 if (cnt == n) return cnt; // 如果已经读够了需要的字符,则返回 e = read4(t); if (e == 0) return cnt; // 如果还需要继续读字符但是读出的字符数为0 return cnt + read(buf + cnt, n - cnt); // 如果还需要继续读字符,递归 }
int i = 0, e = 0; // 维护全局buffer的下标和右边界(不一定为4) char t[4]; };