0
#include <bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int a, b;
        cin >> a >> b;
        if (a == b) cout << 0 << endl;
        else cout << 1 + int((a < b) ^ ((b - a) & 1)) << endl;
    }

    return 0;
}

please someone describe the above statement.how this statement works and what is the result of this statement. this code is snippet from codeforces. link:https://codeforces.com/blog/entry/74224

R Sahu
  • 204,454
  • 14
  • 159
  • 270
ZeroToOne
  • 9
  • 3

1 Answers1

2

Let's make it step by step.

  1. c = (b - a) & 1 - check if last bit of b - a is set, same as check that b - a is odd.
  2. d = (a < b) ^ c - returns true if int(a < b) != c.
  3. 1 + int(d) - should be clear

Then we have

             (b - a) - odd          (b - a) - even
(a < b)           1                       2
(a >= b)          2                       1
Tarek Dakhran
  • 2,021
  • 11
  • 21
  • I wonder why the author wasted lines... Instead of `if`-`else`, she/he could've written: `std::cout << (a != b) * (1 + int((a < b) ^ ((b - a) & 1))) << std::endl;`. ;-) – Scheff's Cat Feb 25 '20 at 07:08
  • 1
    In your line 2, the conversion actually goes the other way. The type of `a < b` is `bool` and the type of `c` is `int`, so `a < b` gets promoted to `int`, with the value `0` or `1`. It doesn't affect the result here, since `c` is 0 or 1, but be very careful when comparing `bool` values with `int` values. `int i = 2; if (i) f();` will call `f()`, but `int i = 2; if (i == true) f();` will not. – Pete Becker Feb 25 '20 at 15:51