Solve #42 in scala