Solve #30 in scala