Thursday, March 24, 2016

LeetCode Q157: Read N Characters Given Read4

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 read function will only be called once for each test case.

// 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:
// 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);
}
};
view raw Q157Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment