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.

答案

public class Solution extends Reader4 {
    public int read(char[] buf, int n) {
        
        int total_bytes_read = 0;
        char[] buf4 = new char[4];
        
        while(n > total_bytes_read) {
            int bytes_read = read4(buf4);
            // If we've read more than we need, set bytes_read to what we need
            if(total_bytes_read + bytes_read > n)
                bytes_read = n - total_bytes_read;
            // Copy
            for(int i = 0; i < bytes_read; i++) {
                buf[total_bytes_read + i] = buf4[i];
            }
            // Accumulate
            total_bytes_read += bytes_read;
            // EOF
            if(bytes_read < 4) break;
        }
        
        return total_bytes_read;
        
    }
}

你可能感兴趣的:(Read N Characters Given Read4)