The API:
int read4(char *buf)
reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the
read4
API, implement the function int read(char *buf, int n)
that reads n characters from the file.
Note:
The
The
read
function will only be called once for each test case.
This file contains 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 | |
*/ | |
int read(char *buf, int n) { | |
int p=0; | |
int count=0; | |
while(true){ | |
char _buf[4]; | |
int _n=read4(_buf); | |
for(int i=0; i<_n; i++){ | |
if(count==n) | |
return n; | |
buf[p++]=_buf[i]; | |
count++; | |
} | |
if(_n<4) | |
return count; | |
} | |
} | |
}; |
Round 2 solution:
This file contains 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 | |
*/ | |
int read(char *buf, int n) { | |
int res=0; | |
int local=4; | |
while(res<n&&local==4){ | |
local=read4(buf); | |
res+=local; | |
buf+=local; | |
} | |
return min(n, res); | |
} | |
}; |
No comments:
Post a Comment