Solution sharing Java beats 95% O(m+n)


  • 0
    M
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(l1 == null){
                return l2;
            }
            if(l2 == null){
                return l1;
            }
            
            ListNode result = new ListNode(0);
            ListNode head = result;
            int carry = 0;
            
            while(l1 != null || l2!=null){
                int value = 0;
                if(l1 != null){
                    if(l2 != null){
                        value = l1.val + l2.val + carry;
                    }
                    else{
                        value = l1.val + carry;
                    }
                }          
                else if(l2 != null){
                    value = l2.val + carry;
                }
    
                carry = value/10;
                value = value%10;
                result.val=value;
                l1 = l1!=null?l1.next:null;
                l2 = l2!=null?l2.next:null;
                
                if(l1 !=null || l2 != null){
                    result.next = new ListNode(0);
                    result = result.next;
                }
            }
            if(carry > 0){
                result.next = new ListNode(carry);
            }
            return head;
        }
    }
    

Log in to reply
 

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