Official

B - CTZ Editorial by en_translator


The value \(\text{ctz}(n)\) can be obtained by performing the procedure operation for \(i=1,2,\ldots\) in order:

  1. Refer to the \(i\)-th least significant digit in the binary representation of \(n\).
  2. Do nothing if it is \(0\).
  3. If it is 1, immediately terminate the procedure. The current value of \(i\) subtracted by \(1\) equals sought \(\text{ctz}(n)\).

Here, the \(i\)-th least significant digit (0 or 1) in the binary representation of \(n\) can be obtained by taking the logical product (AND) of \(n\) shifted \((i-1)\) bits to the right.
Since \(n\leq 10^9<2^{30}\), the iteration above is repeated at most \(30\) times, which finishes within sufficiently short time. Therefore, the problem has been solved.
(Reference: ビット演算について (“Bit operation”, Japanese))

Alternatively, one can store the bit sequence in the binary representation of \(n\) in an array of integers or booleans, or inspect the last bit while right-shifting \(n\) one by one. These are all fast enough.


If you are not very used to handling bit sequences, you can regard each step as an operation against an integer. They can be regarded as:

  • the \(i\)-th least significant digit in the binary representation of \(n\) \(\to\) remainder when \(n\) is divided by \(2\);
  • shifting \(n\) to the right by one bit \(\to\) dividing \(n\) by \(2\) (with fractional part rounded down).

Thus, the effectively same operations can be achieved by combining these operations.
Under the constraints of this problem, it is fast enough.

Intermediate and rather difficult problems sometimes require constant-factor optimization using say bitsets, which is based on bit operations which tend to be fast, so it may be good idea to learn bit operations.

Sample code in C++

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n;
	cin>>n;
	for(int i=0;;i++){
		if(n&(1<<i)){
			cout<<i<<endl;
			return 0;
		}
	}
}

Sample code in Python

n=int(input())
for i in range(30):
    if n&(1<<i):
        print(i)
        break

posted:
last update: