Read N Characters Given Read4
给一个read4的方法, 求写一个read方法. 主要是判断两个情况, 第一个是读不够, 第二个是只读前n个. 读不够就返回当前的i. 读前n个需要判断当前的t和n-i的那个小.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * The read4 API is defined in the parent class Reader4. * int read4(char[] buf); */ public class Solution extends Reader4 { /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ public int read(char[] buf, int n) { int i = 0; char[] c = new char[4]; int t = 0; do{ t = read4(c); if(t <= 0) break; t = Math.min(t, n - i); for(int j = 0; j < t; j++) { buf[i++] = c[j]; } }while(true); return i; } } |