Implemented qiangxue's solution as it is much simpler.