fork download
  1. import java.io.IOException;
  2. import java.math.BigInteger;
  3.  
  4. class Scratch {
  5. static BigInteger bitsRead = BigInteger.ZERO;
  6. static boolean readBit() throws IOException {
  7. int readByte = System.in.read();
  8.  
  9. if (readByte < 0) {
  10. throw new IllegalStateException("Unexpected end of bit-stream");
  11. }
  12.  
  13. if (readByte != '0' && readByte != '1') {
  14. throw new IllegalStateException("Only ASCII 0 and 1 are allowed");
  15. }
  16.  
  17. bitsRead = bitsRead.add(BigInteger.ONE);
  18.  
  19. return readByte == '1';
  20. }
  21.  
  22. private static void writeBit(boolean bit) {
  23. System.out.print(bit ? "1" : "0");
  24. }
  25.  
  26. static BigInteger readNumber(BigInteger length) throws IOException {
  27. BigInteger number = BigInteger.ZERO;
  28.  
  29. while (length.signum() > 0) {
  30. number = number.shiftLeft(1).add(readBit() ? BigInteger.ONE : BigInteger.ZERO);
  31.  
  32. length = length.subtract(BigInteger.ONE);
  33. }
  34.  
  35. return number;
  36. }
  37.  
  38. public static void main(String[] args) throws IOException {
  39. if (readBit()) {
  40. throw new IllegalStateException("parameter K must be at least 1");
  41. }
  42.  
  43. BigInteger x_i = readNumber(BigInteger.valueOf(2));
  44.  
  45. while (!readBit()) {
  46. x_i = readNumber(x_i);
  47. }
  48.  
  49. System.out.println("Number of bits read so far: " + bitsRead);
  50. System.out.println("Now will read the bit-sequence of length: " + x_i);
  51.  
  52. while (x_i.signum() > 0) {
  53. writeBit(readBit());
  54.  
  55. x_i = x_i.subtract(BigInteger.ONE);
  56. }
  57. }
  58. }
Success #stdin #stdout 0.12s 52104KB
stdin
011010011000
stdout
Number of bits read so far: 8
Now will read the bit-sequence of length: 4
1000