158. Read N Characters Given Read4 II - Call multiple times
Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
private:
char buf4[4];
int buf4Index = 4;
int buf4Size = 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 i = 0;
while(i < n){
// check calling API condition
if(buf4Index >= buf4Size){
buf4Size = read4(buf4);
if(buf4Size == 0) break;
buf4Index = 0;
}
buf[i] = buf4[buf4Index];
i++;
buf4Index++;
}
return i;
}
};Last updated
Was this helpful?