Java O(n) time O(1) space short solution


  • 0

    The idea is to find the first non-nine node from the right.
    Increase its val by 1 and change everything behind it to zero.

    public ListNode plusOne(ListNode head) {
        ListNode notNine = new ListNode(0);
        notNine.next = head;
        head = notNine;
        for (ListNode node = head; node != null; node = node.next)
            if (node.val != 9) notNine = node;
        notNine.val += 1;
        for (ListNode node = notNine.next; node != null; node = node.next)
            node.val = 0;
        return head.val > 0 ? head : head.next;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.