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

    Solution:

     1 /* The read4 API is defined in the parent class Reader4.
     2       int read4(char[] buf); */
     3 
     4 public class Solution extends Reader4 {
     5     /**
     6      * @param buf Destination buffer
     7      * @param n   Maximum number of characters to read
     8      * @return    The number of characters read
     9      */
    10     public int read(char[] buf, int n) {
    11         char[] tempBuf = new char[4];
    12         int left = n;
    13         while (left>0){
    14             int num = read4(tempBuf);
    15             //if the read number is larger then what we need, then we just put the left number of chars into buf.
    16             int end = Math.min(num,left);
    17             for (int i=0;i<end;i++){
    18                 buf[n-left] = tempBuf[i];
    19                 left--;
    20             }
    21   
    22             //If reach EOF.
    23             if (left>0 && num<4) break;
    24         }
    25          
    26         return n-left;   
    27         
    28     }
    29 }
  • 相关阅读:
    mysql日期默认值格式('0000-00-00')错误解决
    休闲一下-精华-IMDB评分8分左右影片400多部!
    开机动画流程
    SystemServer启动服务
    理解Android进程创建流程
    android开机动画启动流程
    Android系统的启动优化
    Android 系统启动(init,zygote)
    Zygote
    init
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4160859.html
Copyright © 2011-2022 走看看