Solve the HDOJ1016

The test case is not easy to add. I will refactor the code to add unit
tests.