P171: Added explanation and comments, tweaked Java solution.