zoukankan      html  css  js  c++  java
  • 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.

    解答:

     1 public class Solution extends Reader4 {
     2 
     3     public int read(char[] buf, int n) {
     4         char[] buffer = new char[4];
     5         int readBytes = 0;
     6         boolean eof = false;
     7 
     8         while(!eof && readBytes < n) {
     9             int sz = read4(buffer);
    10             if(sz < 4) {
    11                 eof = true;
    12             }
    13 
    14             int bytes = Math.min(n-readBytes, sz);
    15             // buffer:src
    16             // buf:dst
    17             // readBytes:destPos
    18             // bytes:length
    19             System.arraycopy(buffer, buf, readBytes, bytes);
    20             readBytes = readBytes + bytes;
    21         }
    22 
    23         return readBytes;
    24     }
    25 }
  • 相关阅读:
    vue 響應接口
    vue ajax
    vue混入
    vue動畫和過渡
    vue路由
    vue自定義指令
    python项目_使用极验验证码
    python项目_使用异步功能,celery
    python项目_集成短信发送功能
    python项目_redis使用
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10403177.html
Copyright © 2011-2022 走看看