C++ concise solution.


  • 10
    C
    int read(char *buf, int n) {
        int res = 0;
        while (n > 0) {
            int tmp = min(read4(buf), n);
            res += tmp;
            buf += tmp;
            if (tmp < 4)
                break;
            n -= 4;
        }
        return res;
    }

  • 0
    G

    Nice and clean solution :)


  • 3

    said in C++ concise solution.:

    int tmp = min(read4(buf), n);

    If n<4, read4(buf) may write out of bounds of buf.


  • 0
    Z
    This post is deleted!

  • 0
    P
        int read(char *buf, int n) {
            int res = 0;
            while(n > 0){
                int t = min(n, read4(buf));
                n -= t;
                res += t;
                buf += t;
                if(t < 4)break;
            }
            return res;
        }
    };
    

    You should subtract t from n, instead of 4. In my opinion that is "more correct". The condition (n > 4) and (t < 4) is sufficient.


  • 0
    Y

    @yu6
    I think this change will be more correct:

    int record=0;
    int readSum=0;
    while(n>0)
    {
    int temp=read4(buf);
    readSum+=temp;
    int once=min(temp,n);
    buf+=once;
    record+=once;
    n-=once;
    if(once<4)break;
    }

        if(readSum>record)
        {
            for(int i=record-1;i<readSum;i++)
            {
                buf[i]='0';
            }
        }
        return record;

  • 0
    N

    this solution is not good, destination buffer "buf" is not as expected.


  • 0
    F

    Anyone not using an intermediate buffer will slip in the buffer overflow bug. LeetCode test cases should be smart and check for buffer overflows. Your solution can't exist in a real world code. I am sorry.


  • 0
    N

    @Filis Hi, I believe lc has updated test case. They are checking the buf now.


Log in to reply
 

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