Suppose, in a mathematical program, I have $n$ binary variables arranged in a vector ($x\in \{0,1\}^n$), and I want an integer variable $z\in \mathbb{Z}$ to equal the number of initial zeros in $x$. If $x=0$ I want $z=n$, if $x=(1,\dots)$ I want $z=0$, if $x=(0,0,0,1,\dots)$ I want $z=3$, and so on. It turns out I can do this with $2n$ additional constraints and no additional decision variables. (Programming note: I'm using mathematical notation, i.e., one-based indexing. If you are coding in a language with zero-based indexing, such as C++ or Java, keep an eye out for adjustments.)
The following two sets of constraints do the job:
\begin{eqnarray*}
z & \le & n-(n-k+1)x_{k},\: k=1,\dots,n\\
z & \ge & k-n\sum_{j=1}^{k}x_{j},\: k=1,\dots,n.
\end{eqnarray*}
The proof is left to the reader as an exercise. The first set of constraints will be unnecessary if overestimating the count would hurt the model's objective value; the second set is unnecessary if underestimating the count would hurt the model's objective value.
I make no claim that this is the best formulation, just that it works. The first set of constraints is sparse but the second set unfortunately is not, so hopefully this would not need to be done a large number of times in the model.
Minor tweaks to this approach will allow you to count the number of initial ones rather than zeros, or find the index of the first one in $x$ (assuming $x\neq 0$).