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 }
  • 相关阅读:
    CSU 1333 Funny Car Racing
    FZU 2195 检查站点
    FZU 2193 So Hard
    ZOJ 1655 FZU 1125 Transport Goods
    zoj 2750 Idiomatic Phrases Game
    hdu 1874 畅通工程续
    hdu 2489 Minimal Ratio Tree
    hdu 3398 String
    洛谷 P2158 [SDOI2008]仪仗队 解题报告
    POJ 1958 Strange Towers of Hanoi 解题报告
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4160859.html
Copyright © 2011-2022 走看看