zoukankan      html  css  js  c++  java
  • [leetcode]Read N Characters Given Read4 II

    leetcode上面写的难度是hard,其实很简单,前面也写了,加个buffer就好了。

    // 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
         */
        Solution() : buf_len(0) {
            
        }
        int read(char *buf, int n) {
            char buffer[5];
            int cnt = 0;
            if (buf_len > 0) {
                memcpy(buf, _buf, min(buf_len, n));
                cnt += min(buf_len, n);
                if (n < buf_len) {
                    memcpy(_buf, _buf + n, buf_len - n);
                    buf_len -= n;
                } else {
                    buf_len = 0;
                }
            }
            int sz;
            while(cnt < n) {
                sz = read4(buffer);
                memcpy(buf + cnt, buffer, sz);
                cnt += sz;
                if (sz < 4) break;
            }
            if (cnt > n) {
                buf[n] = '';
                buf_len = cnt - n;
                memcpy(_buf, buffer + (sz-buf_len), buf_len);
                cnt = n;
            }
            return cnt;
        }
    private:
        int buf_len;
        char _buf[5];
    };
  • 相关阅读:
    nodejs install
    taobao sass
    Cors 跨域访问API
    多文件上传
    Next
    实用小工具
    下载包含src,tgz,zip的文件
    HTML5文件API
    Bootstrap (导航、标签、面包屑导航)
    Bootstrap 固定定位(Affix)
  • 原文地址:https://www.cnblogs.com/x1957/p/4118072.html
Copyright © 2011-2022 走看看