JAVA Share my AC solution reverse->add->reverse


  • 0
    H

    Not the best solution but it was the one of problems I submitted it before went into the discussion for answers. XD
    Please help me optomize it, open to suggestions.

    public ListNode plusOne(ListNode list) {
        ListNode fake = reverse(list);
    	ListNode sumList = new ListNode(0);
    	ListNode fakeSum = sumList;
    	int sum = 1;
    	while (fake != null) {
    	        sum += fake.val;
    	sumList.next = new ListNode(sum % 10);
    		sum = sum / 10;
    		fake = fake.next;
    		sumList = sumList.next;
    	}
    	if (sum == 1) {
    		sumList.next = new ListNode(1);
    		sumList = sumList.next;
    		return reverse(fakeSum.next);
    	}
    	if (sum / 10 == 1) {
    		sumList.next = new ListNode(1);
    		sumList = sumList.next;
    	}
    	return reverse(fakeSum.next);
    }
    public static ListNode reverse(ListNode list) {
    	ListNode prev = null;
    	while (list != null) {
    		ListNode temp = list.next;
    		list.next = prev;
    		prev = list;
    		list = temp;
    	}
    	return prev;
    }

Log in to reply
 

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