forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
158. Read N Characters Given Read4 II - Call multiple times.cpp
88 lines (83 loc) · 1.8 KB
/
158. Read N Characters Given Read4 II - Call multiple times.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Forward declaration of the read4 API.
int read4(char *buf);
// Solution 1.
class Solution {
private:
int ptr = 0;
char* tmp = new char[4];
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int cnt = 0;
int k;
while(cnt < n){
if(ptr == 0) k = read4(tmp);
if(k == 0) break;
while(cnt < n && ptr < k){
buf[cnt++] = tmp[ptr++];
}
if(ptr == k) ptr = 0;
}
return cnt;
}
};
// Solution 2.
class Solution {
private:
int p = 4;
int i = 4;
char tmp[4];
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int sum = 0;
while(sum < n){
if(p == i){
i = read4(tmp);
p = 0;
}
if(i == 0) break;
*buf++ = tmp[p++];
sum++;
}
return sum;
}
};
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int count = 0;
while (n) {
if (p == cnt) {
cnt = read4(tmp);
p = 0;
}
if (cnt == 0) {
break;
}
*buf++ = tmp[p++];
++count;
--n;
}
return count;
}
private:
int p = 4;
int cnt = 4;
char tmp[4];
};