[LeetCode157]Read N Characters Given Read4

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.

这道题读懂题目,花了好多时间:其实,题目让我们实现的功能就是通过他本来给你的这个read4(char buf) function 去实现一个 read(char* buf, int n)* function. 这个方程干什么的? 就是说我有一个file, 和另一个空白地儿 (let’s say it char* buf). read4将一次读4个char 并且返回它读了几个,到我们的空白空间里去, 但如果最后, file不足4个char, 它就返回真实的char的个数。 所以利用这个函数, 我们要实现一个以此可以读n个char到我们需要的空白空间去的函数。这题简单(。。吗?)之处就在于我们实现的新函数只被call了一次,就完事了。所以actually, there are two special situations:
case 1: file size = 50, n = 23. That means, 我们只需要23个char,然而file有50个,所以最后一次即使read4会读四个char到它自己的buffer里,我们不能取所有的,只copy它前三个char到我们的buffer里就可以了!所以我们得数着到底读了多少还剩多少。
case2:file size = 14, n = 23. That means, 我们即使可以读23个,但actually没有那么多char 让你读, 所以当 read4 < 4时,就可以停了!

看到一个博主的code, 利用oneRead( from read4), haveRead(total size we have read) and actualRead( the actual number we read from tmpBuf) 可以让code更easyunderstand一点。。

oneRead = read4(tmpBuf);
actualRead = min(n - haveRead, oneRead);
haveRead += actualRead;

最后附上code:

int read(char *buf, int n) {
    char* tmpBuf = new char[4];
    int haveRead = 0, oneRead = 0, actualRead = 0;
    while(haveRead < n){
        oneRead = read4(tmpBuf);
        if(oneRead < 4) break;
        actualRead = min(n-haveRead, oneRead);
        for(int i = 0; i < actualRead; ++i){
           buf[haveRead + i] = tmpBuf[i];
        }
        haveRead += actualRead;
    }
    if(haveRead == n) return haveRead;
    else if(oneRead < 4){
       actualRead = min(n-haveRead, oneRead);
       for(int i = 0; i < actualRead; ++i){
          buf[haveRead + i] = tmpBuf[i];
       }
       haveRead += actualRead;
       return haveRead;
   }
}

或者用一个flag简化code:

    int read(char *buf, int n) {
        char* tmpBuf = new char[4];
        int haveRead = 0;
        bool lessThan4 = false;
        while(!lessThan4 && haveRead < n){
            int oneRead = read4(tmpBuf);
            if(oneRead < 4) lessThan4 = true;
            int actualRead = min(n-haveRead, oneRead);
            for(int i = 0; i<actualRead; ++i){
                buf[haveRead + i] = tmpBuf[i];
            }
            haveRead += actualRead;
        }
        return haveRead;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值