码迷,mamicode.com
首页 > 其他好文 > 详细

158. Read N Characters Given Read4 II - Call multiple times

时间:2018-08-17 01:19:18      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:returns   time   poi   public   multi   private   data   pre   class   

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 ""
Example 2: 

Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""

   

    private int buffPtr = 0;
    private int buffCnt = 0;
    private char[] buff = new char[4];
    public int read(char[] buf, int n) {
        int ptr = 0;
        while (ptr < n) {
            if (buffPtr == 0) {
                buffCnt = read4(buff);
            }
          
            if (buffCnt == 0) break;
          
            while (ptr < n && buffPtr < buffCnt) {
                buf[ptr++] = buff[buffPtr++];
            }
          
            if (buffPtr >= buffCnt){
              buffPtr = 0;
            }
        }
        return ptr;
    }
I used buffer pointer (buffPtr) and buffer Counter (buffCnt)
  to store the data received
in previous calls. In the while loop,
if buffPtr reaches current buffCnt, it will be set
as zero to be ready to read new data.

 

158. Read N Characters Given Read4 II - Call multiple times

标签:returns   time   poi   public   multi   private   data   pre   class   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9490943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!