The digits are stored such that the most significant digit is at the head of the list.
public class Solution { public int[] plusOne(int[] digits) { // Consider a special case that should change the dimension of result (digits = {9,9,9,...}) int n = digits.length; boolean allNine = true; for (int i = 0; i < n; i++) if (digits[i] != 9) { allNine = false; break; } if (allNine) { int[] result = new int[n+1]; result[0] = 1; return result; } else { int[] result = new int[n]; int i, j; for (i = n-1; i >= 0; i--) if (digits[i] == 9) result[i] = 0; else { result[i] = digits[i]+1; break; } for (j = i-1; j >= 0; j--) result[j] = digits[j]; return result; } } }
No comments:
Post a Comment