Enjoy the mess, as long as it works out


  • 0
    D
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode t1 = l1;
            ListNode t2 = l2;
            
            // 
            while (t1.next != null && t2.next !=null) {
                int temp  = (t1.val+t2.val) / 10;
                t1.val = (t1.val+t2.val) % 10;
                t1 = t1.next;
                t2 = t2.next;
                t1.val += temp;              
            }
            
            int temp  = (t1.val+t2.val) / 10;
            t1.val = (t1.val+t2.val) % 10;
    
            if (temp == 0 ){
                if (t1.next == null) t1.next = t2.next;
            }
            
            else {
                if (t1.next == null && t2.next == null) 
                {
                    t1.next = new ListNode(1); }
                else {if (t1.next != null ) t1.next.val++;
                else 
                    {t1.next = t2.next; t1.next.val++;}
                     }
                t1= t1.next;
    
            if(t1 !=null){
             while (t1.val == 10 ){
                t1.val = 0;
                if (t1.next == null) t1.next = new ListNode(1);
                else {t1= t1.next; t1.val++;}
            }
           }
            }
            
            
            return l1;
        }
    }
    

Log in to reply
 

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