Accepted Java solution, using only ListNode as data structure


  • 1
    A
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      if (l1 == null && l2 == null) return null;
      if (l1 == null ) return l2;
      if (l2 == null ) return l1;
      ListNode head=null, prev=null;
      int carryOver = 0;
      int singleDigit = 0;
      boolean continues = true;
      do {
          int val1=0, val2=0;
          if (l1 != null) val1 = l1.val;
          if (l2 != null) val2 = l2.val;
          int res = val1 + val2 + carryOver;
          singleDigit = getSingleDigit ( res );
          carryOver = res / 10;
          ListNode n = new ListNode(singleDigit);
          if ( head == null )
              head = n;
          else
              prev.next = n;
          prev = n;
          if (l1 != null) l1 = l1.next;
          if (l2 != null) l2 = l2.next;
          if (l1 == null && l2 == null) continues = false;
      } while (continues);
      if (carryOver>0) {
          ListNode n = new ListNode(carryOver);
          prev.next = n;
      }
      return head;
    }
    public int getSingleDigit ( int res) {
        if (res >= 10)
            return res % 10;
        else
            return res;
    }
    

    }


  • 0
    Z

    similar logic, how come my solution can't be accepted. I got the [0], [0] run error. I ran it on local with test cases, it all passed. below is my solution:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    boolean overTen = false;
    ListNode result = l1;
    ListNode previous = l1;

    	if (l1 == null) return l2;
    	if (l2 == null) return l1;
    
    	while (l1 != null) {
    		if (l2 != null) {
    			int tmpVal = l1.val + l2.val + (overTen ? 1 : 0);
    			l1.val = tmpVal %10;
    			overTen = tmpVal / 10 > 0;
    		}
    		else if (overTen) {
    			overTen = (l1.val + 1 ) / 10 > 0;
    			l1.val = (l1.val + 1) %10;
    		}
    		else {
    			return result;
    		}
    		previous = l1;
    		l1 = l1.next;
    		l2 = l2.next;
    	}
    
    	previous.next = l2;
    	while (l2 != null) {
    		if (overTen) {
    			int tmp = (overTen ? 1 : 0) + l2.val;
    			l2.val = tmp % 10;
    			overTen = tmp / 10 > 0;
    			previous = l2;
    			l2 = l2.next;
    		}
    	}
    	if (overTen) {
    		ListNode last = new ListNode(1);
    		previous.next = last;
    	}
    
    	return result;
    

    }


Log in to reply
 

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