Created
August 17, 2017 15:55
-
-
Save rebelmachina/561b9063f97618f8f95f6ec43214113f to your computer and use it in GitHub Desktop.
Read N Characters Given Read4 II - Call multiple times: LEETCODE SOLUTION
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 | |
| */ | |
| char buf4[4]; // temporary buffer in case we read more caracters than n. | |
| int i4 = 0, n4 = 0; // current index i4 in buf4 and its length in n4. | |
| int read(char *buf, int n) { | |
| int i = 0; | |
| while (i < n) { // while we have read how much we wanted | |
| if ((n4 > 0 && i4 == n4)||n4 == 0) { // either we read everything from buf4, or we didn't read anything yet. | |
| i4 = 0; | |
| n4 = read4(buf4); // read next characters from the file and store them in the buffer. | |
| if (n4 == 0) { // we didn't read any new characters, so we exit. | |
| break; | |
| } | |
| } | |
| buf[i++] = buf4[i4++]; // copy the read characters from the buffer to the destination. | |
| } | |
| return i; // return the current number of read characters. | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment