On average, the last $P$ pages have $r=\frac DP$ digits.
If $r$ is an integer, then any $Q$ with $10^{r-1}+P-1\le Q\le 10^r-1$ is a solution, provided $10^{r-1}+P-1\le 10^r-1$ (i.e., $P\le 9\cdot 10^{r-1}$).
If on the other hand $P> 9\cdot 10^{r-1}$, then $Q$ must be $\ge 10^r$; more precisely we need to have as many $(r+1)$-digit pages as $(r-1)$-digit pages, so $Q=10^r-1+\frac{P-9\cdot 10^{r-1}}2$ - unless that makes $Q-P<10^{r-1}$, in which case we have to adjust $Q$ once again. Ultimately, this would boil down to some kind of binary search.
If $r$ is not an integer, there will be at most one valid $Q$. We can find a first approximation by assuming that we start with $\lfloor r\rfloor$-digit numbers and end with $P\cdot(r-\lfloor r\rfloor)$ numbers with $\lfloor r\rfloor +1$ digits. That would make $Q=10^r+P\cdot(r-\lfloor r\rfloor)-1=10^r+(D\bmod P)-1$. However, if this makes $Q\ge 10^{r+1}$ or $Q-P+1<10^r$, we have to do some fine-tuning similar to the first case, again with a kind of binary search.