Recursive Java solutions Easy to understand


  • 0

    '''
    public class Solution {
    public ListNode plusOne(ListNode head) {
    int first = helper(head);
    if(first==1){ //If first call also return remainder of 1 then add new node with val 1 and return that
    ListNode newHead = new ListNode(first);
    newHead.next=head;
    return newHead;
    } else {
    return head;
    }
    }

    public int helper(ListNode head){
        if(head.next==null){ //Last node add one and send the remainder back
            int sum = head.val+1;
            head.val=sum%10;
            return sum/10;
        } else { //Send the remainder back
            int sum = head.val+helper(head.next);
            head.val=sum%10;
            return sum/10;
        }
    }
    

    }
    '''


Log in to reply
 

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