I already have the solution of this task, this code passed the tests. But I don't understand it.
And I don't have
other part of the code, only this method. I should complete it and pass the tests.
Code of the tests I don't have too.
The solution:
public static int getSum(InputStream is) {
int sum = 0;
try {
int digit = is.read();
while (digit != -1) {
sum += digit;
}
}catch (Exception e){
e.printStackTrace();
}
return sum;
}
For example, if InputStream contains 1,2,10 then sum would be 13.
But how the program find 13 If is.read()
method return byte representation of inputed digits instead of the certain digits?
It should be sum of 49 + 50 + (what is byte representation of 10? ) = more then 13
If the numbers that are read are present in the input stream in the same binary format Java uses (twos complement, big endian), reading them into an int will work as expected.
However, as only a single byte is read into the 4byte java int, a solution will only work with numbers that happen to have all but the last 8 bit set to zero in 32 bit twos complement representation - that's positive numbers from 0 to 127.