Friday, March 20, 2015

Read N Characters Given Read4 -- Leetcode

Question:
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.



Answer:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {

        int readNumRes=0;
        int m = n/4;
         
        for(int i=0;i<m;++i){
   
            int readNum = read4(buf);
            buf+=readNum;
            readNumRes+=readNum;
         
            if(readNum < 4){
                return readNumRes;     //return firstly!
            }
        }
     

        // Last several bytes should be condsider seperately, still has chars to read in the file
        int q = n%4;
        char tmpBytes[5];  //tmp bytes space for last read4(), space is 5, include '\0'!
       
        //For example: "ab", read(1); can not use read4(buf) directly, lastNum = 1, q=1, readNum=2 in the case!

        int readNum = read4(tmpBytes);
        int lastNum = q < readNum ? q : readNum;
     
        for(int i=0;i<lastNum;++i){
            *(buf+i) = tmpBytes[i];           //!important
        }
        readNumRes += lastNum;
        return readNumRes;
    }
};

No comments:

Post a Comment