Solve #35 in scala