I came across this problem while studying modular forms (while proving the integrality of the $j$-invariant) but I guess that the solution can found in some linear algebra reasoning.
Given $$T=\begin{pmatrix} a & b \\ 0& d \end{pmatrix}\in M_2(\mathbb{Z})$$ such that $ad=n$, $0\leq b <d$.
I would like to show that $$ T= A \begin{pmatrix} d_1& 0 \\ 0 & d_2 \end{pmatrix} B $$ for some $A,B \in SL_2(\mathbb{Z})$ and $d_1d_2=n$, $d_2\mid d_1$
I had some ideas considering the matrices of $SL_2(\mathbb{Z})$ as base changes of $\mathbb{Z}^2$ and $T,\begin{pmatrix}d_1&0\\0& d_2 \end{pmatrix}$ as endomorphisms of $\mathbb{Z}^2$, but I couldn't figure out the way to do it.
Any hint or reference that treats integer matrices problems like this one would be appreciated as much as a solution.