Java solution with annotation


  • 0
    R
    public int read(char[] buf, int n) {    // buf is the destination
    // read4 will always overwrite first 4 position of char[], so we use temp to temporarily store data
        char[] temp = new char[4]; 
    //  when readNum is not 4, it means we readed all the data from file
        int readNum = 0;   
        int index = 0;
        int res = 0;
        do {
            readNum = read4(temp);
    // only read "readNum" chars
            for(int i = 0; i < readNum; i++) {
    // check if reach n maximum for every time to write in 
                if(index >= n)  break;
                buf[index++] = temp[i];
                res++;         }
            }
    // when readed all char from file, or reach maximum n char, stop reading more
        while(readNum == 4 && index < n);   
        return res;   
    // default char is '\u0000', OJ will judge the char[] position from 0 to res 
    // so if the res is incorrect, it will contains null character '\u0000'
     }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.