C solution.

Reviewed by @tolmasky.