Modified ex1.16 solution to work with all cases