Solution for problem 146 in java - Not Accepted