Skip to content

Commit 5beb87f

Browse files
committed
implement a more elegant code
1 parent 8e98dd0 commit 5beb87f

1 file changed

Lines changed: 20 additions & 28 deletions

File tree

cpp/ReadNCharactersGivenRead4_2.cc

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,36 @@
11
// https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
22

3-
// Forward declaration of the read4 API.
43
int read4(char *buf);
54

65
class Solution {
76
public:
8-
char tmpBuf[4];
9-
int tmpStart = 0;
10-
int tmpEnd = 0;
11-
bool eof = false;
7+
8+
char myBuf[4];
9+
int myBufStart = 0;
10+
int myBufLen = 0;
11+
1212
/**
1313
* @param buf Destination buffer
1414
* @param n Maximum number of characters to read
1515
* @return The number of characters read
1616
*/
1717
int read(char *buf, int n) {
18-
if (n == 0) return 0;
19-
20-
int count = 0;
18+
int readBytes = 0;
19+
int bufStart = 0;
2120
bool eof = false;
22-
do {
23-
int tmpLen = tmpEnd - tmpStart;
24-
int copyCount = min(tmpLen, n - count);
25-
if (copyCount > 0) {
26-
memcpy(buf + count, tmpBuf + tmpStart, copyCount);
27-
count += copyCount;
28-
tmpStart += copyCount;
21+
while (!eof && readBytes < n) {
22+
if (myBufLen == 0) {
23+
myBufLen = read4(myBuf);
24+
myBufStart = 0;
25+
if (myBufLen < 4) eof = true;
2926
}
30-
if (eof || n == count) {
31-
break;
32-
} else {
33-
int readCount = read4(tmpBuf);
34-
tmpStart = 0;
35-
tmpEnd = readCount;
36-
if (readCount < 4) {
37-
eof = true;
38-
}
39-
}
40-
} while (true);
41-
42-
return count;
27+
int copiedBytes = min(myBufLen, n - readBytes);
28+
memcpy(buf + bufStart, myBuf + myBufStart, copiedBytes);
29+
myBufStart += copiedBytes;
30+
myBufLen -= copiedBytes;
31+
bufStart += copiedBytes;
32+
readBytes += copiedBytes;
33+
}
34+
return readBytes;
4335
}
4436
};

0 commit comments

Comments
 (0)