This question is not the same as -- but has a similar feel to -- the first programming problem in the classic book "Programming Pearls"[1]. You can read it on O'Reilly Safari these days[2].
Even if you don't read the book, that first chapter, "Cracking the Oyster", is worth a read. It's a fun problem.