# Putting the \qed sign at the right place when using answer package

In the following document I have used the package "answer" and when I end a solution I put a \qed sign at the end of solution. This works fine except if the solution terminates with an equation and the \qed goes to the next line which is undesirable.

How to put the \qed at the right place. There are related questions How to put the QED symbol of a proof at the right place inside align? and Pushing \qed to the right within a displayed formula but neither solved my problem.

\documentclass{article}
\renewcommand{\solutionstyle}{\bfseries Answer to Exercise #1 }
\Newassociation{sol}{Solution}{ans}
\newtheorem{ex}{Exercise}
\newcommand\postSolution{\hfill\qedsymbol}
\begin{document}
\Opensolutionfile{ans}[ans1]

\begin{ex}
First exercise
\end{ex}

\begin{sol}
First solution
$A=B.$
\end{sol}

\Closesolutionfile{ans}
\input{ans1}
\end{document}


You can patch Solution to work like proof in amsthm:

\documentclass{article}

\renewcommand{\solutionstyle}{\bfseries Answer to Exercise #1 }
\Newassociation{sol}{Solution}{ans}
\newtheorem{ex}{Exercise}

\xpretocmd{\Solution}{\pushQED{\qed}}{}{\ddt}
\xpatchcmd{\endSolution}{\endtrivlist}{\popQED\endtrivlist}{}{\ddt}

\begin{document}

\Opensolutionfile{ans}[ans1]

\begin{ex}
First exercise
\end{ex}

\begin{sol}
First solution
$A=B.\qedhere$
\end{sol}

\begin{ex}
Second exercise
\end{ex}

\begin{sol}
Second solution
$A=B.$
Some words follow.
\end{sol}

\Closesolutionfile{ans}
\input{ans1}
\end{document} 