Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
public int[] plusOne(int[] digits) {
if (digits == null)
return null;
// Process the digits in reverse order
for (int i = digits.length-1; i >= 0; i--) {
if (digits[i] < 9) { // Adding 1 ends here
digits[i] += 1;
return digits;
} else { // Add 1 to a higher position
digits[i] = 0;
}
}
// No return from the above; the digits are in the form of 9...9,
// and adding one makes it 10...0
int[] result = new int[digits.length+1];
result[0] = 1;
return result;
}
Read full article from LeetCode - Plus One | Darren's Blog
No comments:
Post a Comment