Official

A - Smaller XOR Editorial by evima


Let us write \(x\) in binary and assume that the most significant bit is at position \(k\) (\(2^k\)). Let us also write \(N\) in binary. If the bit at position \(k\) is \(0\), we have \(N \oplus x > N\). On the contrary, if the bit at position \(k\) is \(1\), we have \(N \oplus x < N\).

Thus, we are done if, for every \(k\) such that the bit of \(N\) at position \(k\) is \(1\), we find the number of integers \(x\) such that \(L \leq x \leq R\) and the most significant bit of \(x\) is at position \(k\).

Here, we can rephrase the latter condition into \(2^k \leq x < 2^{k+1}\), so we just have to count integers \(x\) such that \(\max(L,2^k) \leq x \leq \min(R,2^{k+1}-1)\), which is easy.

Since there are \(O(\log N)\) conditions for \(k\), the total complexity is \(O(\log N)\).

posted:
last update: