O solutie comentata a problemei se poate consulta aici.