Java implementation.
Cpp solution added.