Solved #18 in scala