Quantum counting algorithm and its application in mesoscopic physics