improved @emiswelt cpp solution