Solve #41 in scala