1

У меня есть два метода. Один находит контрольную сумму через цикл, другой через рекурсию. Первый работает правильно, второй нет. Не могу понять почему.

public static void main(String[] args) throws IOException {
    InputStream inputStream1 = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9});
    InputStream inputStream2 = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9});
    System.out.println(recursionCheckSumOfStream(inputStream1) == checkSumOfStream(inputStream2));
}

public static int checkSumOfStream(InputStream inputStream) throws IOException {
    // your implementation here
    int res = 0;
    int readedByte;
    while ((readedByte = inputStream.read()) > 0) {
        res = Integer.rotateLeft(res, 1) ^ readedByte;
    }

    return res;
}

public static int recursionCheckSumOfStream(InputStream inputStream) throws IOException {
    int res = inputStream.read();
    if (res > 0) return Integer.rotateLeft(recursionCheckSumOfStream(inputStream), 1) ^ res;
    else return 0;
}

Результаты работы методов разные. Почему ?

0

1 ответ 1

3

Если вы на бумаге попробует просчитать оба варианта, то увидите, что в цикле вы считаете с начала, а в рекурсии с конца. Давайте возьмем последовательность 1, 2, 3 (для простоты)

В цикле

(((((0 << 1) ^ 1) << 1) ^ 2) << 1) ^ 3 = 3
           0    1     2    0     0     3

Реккурсивно

(((((0 << 1) ^ 3) << 1) ^ 2) << 1) ^ 1 = 9
           0    3     6    4     8     9

"Починить" рекурсивный вариант можно вот так:

InputStream inputStream1 = new ByteArrayInputStream(reverse(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}));

public static byte[] reverse(byte[] a) {
    byte[] res = new byte[a.length];
    for (int i = a.length - 1, j = 0; i >= 0 ; i--, j++) {
        res[j] = a[i];
    }
    return res;
}
1
  • 1
    у вас ведь не просто xor. у вас еще и сдвиг. 3 авг 2017 в 9:38

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.