# 157 Read N Characters Given Read4

Given an API: int read4(char *buf) 一次從某檔案裡讀4個字元,回傳int表示讀取的字元數,當檔案讀到最後時剩不到4個字元,就會只讀剩下的字元數。

寫一個int read(char[] buf, int n),從檔案裡讀n個字元存進buf裡面,若不到n個字元檔案就結束就只讀僅有的內容

  • idea: 題意有點難懂,有偷瞄一下別人解法才理解。當檔案還沒讀完,而且讀的字數total不超過n,就一直用read4讀取,並將當迴圈讀的字數存進total,最後回傳total

  • pseudocode:

            while file not finish, and total < n,
                read4 into tmp, 
                add 4 to total.
                if total read after read4 < n
                    put into buffer
                else
                    remainder = n-(total-4)
                    total = n
                    put remainder char into buf 
    
            return total
    
  • 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) {
            int total = 0;
            int idx = 0;
            boolean eof = false;
    
            while(!eof && total<n){
                char[] tmp = new char[4];
                int count = read4(tmp);
    
                if(count < 4) eof = true;
    
                total+=count;
                if(total < n){
                    for(int i=0; i<4; i++){
                        buf[idx++] = tmp[i];
                    }
                }else{
                    int remainder = n-(total-4);
                    total = n;
                    for(int i=0; i<remainder; i++){
                        buf[idx++] = tmp[i];
                    }
                }
            }
    
            return total;
        }
    }
    

results matching ""

    No results matching ""