Recursive Java straight forward solution


  • 0
    I

    Straight forward solution. The code can be cleaner but the idea is there.

        public ListNode plusOne(ListNode head) {
            int carry = plusOneHelper(head.next);
            int added = head.val + carry;
            head.val = added % 10;
            if ((added / 10) != 0) {
                ListNode newNode = new ListNode(added / 10);
                newNode.next = head; 
                head = newNode;
            }
            return head;
        }
        
        private int plusOneHelper(ListNode head) {
            if (head == null) return 1;
            int carry = head.next != null ? plusOneHelper(head.next) : 1;
            if (carry == 0) return 0;
            int added = head.val + carry;
            head.val = added % 10;
            return added / 10;
        }
    
    

Log in to reply
 

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