Solve #114 in scala