Read N Characters Given Read4

原创 2015年07月08日 23:46:57

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.

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        char[] buffer = new char[4];
        boolean eof = false;
        int read = 0;//number of characters has been read
        
        while(!eof && read < n) {
            int count = read4(buffer);
            int remain = Math.min(count, n - read);
            
            if (count < 4)
                eof = true;
            
            System.arraycopy(buffer, 0, buf, read, remain);
            
            read = read + remain;
        }
        
        return read;
    }
}




相关文章推荐

LeetCode - Read N Characters Given Read4 I && II

https://leetcode.com/problems/read-n-characters-given-read4/ The API: int read4(char *buf) reads 4...

[Leetcode] 158. Read N Characters Given Read4 II - Call multiple times 解题报告

题目: The API: int read4(char *buf) reads 4 characters at a time from a file. The return value...

[LeetCode157]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 actua...

[LeetCode158]Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file.The return value is the actua...

Leetcode 157 & 158 Read N Characters Given Read4 I & II - Call multiple times

157. Read N Characters Given Read4 Total Accepted: 17410 Total Submissions: 58870 Difficulty: Easy ...

leetcode Read N Characters Given Read 4 I/II

The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the a...

Read the b.o.t.N.A.T's sourcecode---1---b.o.t.s.e.r.v.c

下文将记录本文阅读此代码中遇到的名词解释和问题总结,其中会有对多篇他们文章的引用,致谢先。=======================================================...
  • jo_say
  • jo_say
  • 2011年05月30日 17:24
  • 836

read_tmi_averaged_v4

  • 2012年12月29日 08:55
  • 981B
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Read N Characters Given Read4
举报原因:
原因补充:

(最多只允许输入30个字)