// no need to use list // no easy way to convert int[] to Integer list, or Integer list to int[] publicint[] plusOne(int[] digits) { intn= digits.length; intcarry=1; for (inti= n - 1; i >= 0; --i) { intsum= digits[i] + carry; digits[i] = sum % 10; carry = sum / 10; } if (carry > 0) { // need to expand the array int[] newDigits = newint[n + 1]; System.arraycopy(digits, 0, newDigits, 1, n); newDigits[0] = carry; digits = newDigits; } return digits; }
/** * Recursion */ public ListNode plusOne(ListNode head) { // Solve it recursively intcarry= plusOneHelper(head); if (carry > 0) { // need to expand the linked list (add one more node) ListNodenewNode=newListNode(carry); newNode.next = head; head = newNode; } return head; }
// return carry // 1 -> 2 -> 3 -> null // head privateintplusOneHelper(ListNode head) { if (head == null) { return1; // plus one } intcarry= plusOneHelper(head.next); intsum= head.val + carry; head.val = sum % 10; // update node return sum / 10; }