55ms Java straight forward solution


  • 0
    L

    This solution is simple but still cost 55ms. Could anyone share with us a less than 5ms java Solution? Thank you in advance.

    public ListNode addTwoNumbers(ListNode l1, ListNode l2){
            if( l1 == null ) {
                return l2;
            } else if( l2 == null) {
                return l1;
            }
    
            int sum = 0;
            ListNode root = new ListNode(sum);
            /*
                root node will be the end of node after the while loop.
                So use result to point the original root node and return result.
             */
            ListNode result = root;
    
            while (l1!= null || l2 != null) {
                if( l1 != null) {
                    sum += l1.val;
                    l1 = l1.next;
                }
                if( l2!=null) {
                    sum+=l2.val;
                    l2 = l2.next;
                }
    
                if( sum >=10) {
                    root.val = sum - 10;
                    sum = 1;
                } else {
                    root.val = sum;
                    sum = 0;
                }
    
                //sum=1 used for case [5]+[5]=[0,1]
                if( l1!= null || l2 != null || sum ==1 ) {
                    //Avoid add an empty node at the end
                    root.next = new ListNode(sum);
                    root = root.next;
                }
            }
    
            return result;
        }
    

Log in to reply
 

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