File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ /**
4
+ * The API: int read4(char *buf) reads 4 characters at a time from a file.
5
+ *
6
+ * The return value is the actual number of characters read. For example, it returns 3 if there is
7
+ * only 3 characters left in the file.
8
+ *
9
+ * By using the read4 API, implement the function int read(char *buf, int n) that reads n characters
10
+ * from the file.
11
+ *
12
+ * Note: The read function will only be called once for each test case.
13
+ */
14
+
15
+ /**
16
+ * The problem description is pretty ambiguous, actually the problem means to Keep reading until
17
+ * either you have gotten n characters or there is no more characters to read.
18
+ */
19
+ public class ReadNCharactersGivenRead4 {
20
+ public int read (char [] buf , int n ) {
21
+ int index = 0 , next = 0 ;
22
+ char [] buffer = new char [4 ];
23
+ while (index < n && (next = read4 (buffer )) != 0 ){
24
+ for (int i = 0 ; i < next && index < n ; index ++, i ++){
25
+ buf [index ] = buffer [i ];
26
+ }
27
+ }
28
+ return index ;
29
+ }
30
+
31
+ private int read4 (char [] buffer ) {
32
+ //this is a fake method to make Eclipse happy
33
+ return 0 ;
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments