recursive solution


  • 0
    N
    private int add(ListNode node){
    	if(node.next == null){
    		int sum = node.val + 1;
    		node.val = (sum == 10) ? 0 : sum;
    		return (sum==10) ? 1 : 0;
    	}else{
    		int reminder = add(node.next);
    		int sum = node.val + reminder;
    		node.val = (sum == 10) ? 0 : sum;
    		return (sum==10) ? 1 : 0;
    	}
    }
    
    public ListNode plusOne(ListNode head) {
    	int carry = add(head);
    	if(carry == 1){
    		ListNode newNode = new ListNode(1);
    		newNode.next = head;
    		head = newNode;
    	}
    	return head;
    }

Log in to reply
 

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