added solution for some nice problem found on StackOverflow!