0%

157. Read N Characters Given Read4

iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
char t[4];
int i = 0, cnt = 0;
do {
cnt = read4(t);
int j = 0;
while (i < n && j < cnt) {
buf[i++] = t[j++];
}
} while (i < n && cnt == 4); // 注意如果read4读出来的字符少于4个就终止
return i;
}
};

recursive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
char t[4];
int cnt = read4(t), i = 0, j = 0;
if (cnt == 0) return 0;
while (i < n && j < cnt) {
buf[i++] = t[j++];
}
if (i == n) return n;
return cnt + read(buf + cnt, n - cnt);
}
};