Add solution for problem #40

Added solution to problem #40