Java solution for Elements of Programming Interviews book