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 }
  • 相关阅读:
    mysql备份与binlog
    linux释放cached
    linux下mysql迁移到其他分区
    java分析jvm常用指令
    Mac下安装WebStrom
    Final
    Spring 复习
    ubuntu 14.4安装java环境
    php复习
    java 重难点
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10403177.html
Copyright © 2011-2022 走看看