Solve #124 in scala