Plus One

Question (LC.369)

Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list.

Code

public ListNode plusOne(ListNode head) {
    // two pointer approach

    // increment j if less than 9
    // increment i if equal to 9, and zero the rest
    // dummy node is op

    ListNode dummyNode = new ListNode(0);
    dummyNode.next = head;
    ListNode leastSig = dummyNode; // if less than 9
    ListNode mostSig = dummyNode; // if carry is necessary

    // locate leastSig and mostSig
    while (leastSig.next != null) {
        leastSig = leastSig.next;
        if (leastSig.val < 9) mostSig = leastSig;
    }

    // decide which one to increment
    if (leastSig.val < 9) {
        leastSig.val ++;
    } else {
        mostSig.val++;

        mostSig = mostSig.next;
        while (mostSig != null) {
            mostSig.val = 0;
            mostSig = mostSig.next;
        }
    }

    // decide which one to return
    if (dummyNode.val == 1)
        return dummyNode;
    return head;
}

results matching ""

    No results matching ""