My solution for problem on UVa