Yes, of course, you can
As jncraton mentioned in a comment:
The answer to whether this is possible is definitely "yes". NAND gates can be built, and the required logic can be implemented using NAND gates. The questions is primarily about how this can be achieved.
Logic gates in LEGO
As you can see here folks have put extensive work into creating logic gates in LEGO. The article referenced has AND and NOT gates. You would need to put those together to get the aforementioned NAND gate. If you're not familiar with logic gates it may be surprising that NAND gates can do it all.
As this articles shows you can build a binary counter out of flip-flops and NAND's. And as wikipedia shows you can make a variety of flip-flops out of logic gates.
Now put it together
I'm sorry there aren't LEGO-level instructions for making all of this happen, but hopefully those are enough leads for you to figure it out. Good luck. I hope you put this together and turn it into a lovely youtube video or article to show us all how you did it. You'd probably be a hit too on the LEGO convention circuit. You can do it.