Leetcode - Read N Characters Given Read4

My code:

/* 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[] arr = new char[4];
        int counter = 0;
        int num = 4;
        while (num == 4 && counter < n) {
            num = read4(arr);
            for (int i = counter; i < n && i < counter + num; i++) {
                buf[i] = arr[i - counter];
            }
            counter = Math.min(n, counter + num);
        }
       
        return counter;
    }
}

reference:
https://discuss.leetcode.com/topic/52449/java-solution-easy-to-understand

没能自己做出来。没理解题目的意思。后来才知道什么意思。
其实就是每次读4个,读出 n 个 拷贝到 char[] 里面去。

注意点:
1 . 文件里面的字符个数可能 < n
所以 while 判断条件不能只用 counter < n

2 . counter = Math.min(n, counter + temp);

Anyway, Good luck, Richardo! -- 09/20/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容