another and better solution added for comparison. Had trouble with the logic of this one.