- Read N Characters Given Read4
https://leetcode.com/problems/read-n-characters-given-read4/description/
image.png
这道题需要分情况讨论,一种是调用READ4,返回来的数字比4小,代表读完了。
另一种是返回来的就是4.代表还有的读。
后一种情况,如果N已经比4小了。那么就可以输出N了。不然的话N-=4,再调一次READ4。
如果是前一种情况,如果N比返回的数字要大,那么N是读不满的,就要返回实际长度。如果N比返回来的数字要小,那么还是返回N。
public int read(char[] buf, int n) {
char[] tmp = new char[4];
int N = n;
int idx = 0;
while(n>0){
int k = read4(tmp);
if(k==4){
for(int i = 0;i<Math.min(4,n);i++)
buf[idx++] = tmp[i];
if(n<=4){
return N;
}
n-=4;
}else{
for(int i = 0;i<Math.min(k,n);i++)
buf[idx++] = tmp[i];
if(n<=k)
return N;
return idx;
}
}
return N;
}
follow up :
- Read N Characters Given Read4 II - Call multiple times