Solve #112 in scala