/** * The read4 API is defined in the parent class Reader4. * int read4(char *buf4); */classSolution{public:/** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */intread(char*buf,intn){char*buf4=newchar[4];inti4=0;// buf4's indexintn4=0;// buf4's sizeinti=0;// buf's indexwhile(i<n){if(i4==n4){// All characters in buf4 are consumedi4=0;// Reset buf4's indexn4=read4(buf4);// Read 4 (or less) chars from file to buf4if(n4==0)// Reach the EOFreturni;}buf[i++]=buf4[i4++];}returni;}};
/** * The read4 API is defined in the parent class Reader4. * int read4(char[] buf4); */publicclassSolutionextendsReader4{/** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */publicintread(char[]buf,intn){char[]buf4=newchar[4];inti4=0;// buf4's indexintn4=0;// buf4's sizeinti=0;// buf's indexwhile(i<n){if(i4==n4){// All characters in buf4 are consumedi4=0;// Reset buf4's indexn4=read4(buf4);// Read 4 (or less) chars from file to buf4if(n4==0)// Reach the EOFreturni;}buf[i++]=buf4[i4++];}returni;}}
"""The read4 API is already defined for you. def read4(buf4: List[chr]) -> int:# Below is an example of how the read4 API can be called.file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'buf4 = [' '] * 4 # Create buffer with enough space to store charactersread4(buf4) # Read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'read4(buf4) # Read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'read4(buf4) # Read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file"""classSolution:defread(self,buf:List[str],n:int)->int:buf4=[' ']*4i4=0# buf4's indexn4=0# buf4's sizei=0# buf's indexwhilei<n:ifi4==n4:# All characters in buf4 are consumedi4=0# Reset buf4's indexn4=read4(buf4)# Read 4 (or less) chars from file to buf4ifn4==0:# Reach the EOFreturnibuf[i]=buf4[i4]i+=1i4+=1returni